[{"data":1,"prerenderedAt":6629},["ShallowReactive",2],{"home-data":3},{"frameworks":4,"qa":53},[5,16,25,34,44],{"id":6,"description":7,"extension":8,"icon":9,"meta":10,"name":11,"order":12,"slug":9,"stem":13,"tier":14,"__hash__":15},"frameworks\u002Fframeworks\u002Fjavascript.yml","Core JavaScript interview questions covering fundamentals, functions and closures, objects and prototypes, classes and OOP, and asynchronous programming with the event loop.","yml","javascript",{},"JavaScript",1,"frameworks\u002Fjavascript",0,"_TjxyYWBq7dftU9YakX_WX1Z4wAHq9uEUUW7wXL0y0c",{"id":17,"description":18,"extension":8,"icon":19,"meta":20,"name":21,"order":22,"slug":19,"stem":23,"tier":12,"__hash__":24},"frameworks\u002Fframeworks\u002Freact.yml","React interview questions on hooks, components, state and rendering — the most-requested front-end framework in technical interviews.","react",{},"React",2,"frameworks\u002Freact","RA6wemU0xFHrA1ZKCABP1J7MireA3Bt_FCJMOuMgsm0",{"id":26,"description":27,"extension":8,"icon":28,"meta":29,"name":30,"order":31,"slug":28,"stem":32,"tier":12,"__hash__":33},"frameworks\u002Fframeworks\u002Fpython.yml","Python interview questions across language fundamentals, data structures and common gotchas for backend, data and automation roles.","python",{},"Python",3,"frameworks\u002Fpython","QsijsotyAr-3rnhJDWWZmc7hE6HAhylS5t1dKpigMOA",{"id":35,"description":36,"extension":8,"icon":37,"meta":38,"name":39,"order":40,"slug":41,"stem":42,"tier":12,"__hash__":43},"frameworks\u002Fframeworks\u002Fsql.yml","SQL interview questions on queries, joins and aggregation — essential for every backend, data and analytics interview.","database",{},"SQL",4,"sql","frameworks\u002Fsql","lpzsOj2p9p9W0Tctwc61nP-ulZAA80R5gJiyaZS6ZeI",{"id":45,"description":46,"extension":8,"icon":47,"meta":48,"name":49,"order":50,"slug":47,"stem":51,"tier":12,"__hash__":52},"frameworks\u002Fframeworks\u002Fjava.yml","Java interview questions on language fundamentals, object-oriented design, the Collections Framework, exception handling and concurrency — a staple of backend and enterprise technical interviews.","java",{},"Java",5,"frameworks\u002Fjava","jcUKEcQDoMZrreMRtZYJIVpkQlB-varlzbuwmzLr7kc",[54,216,373,521,670,821,965,1103,1242,1377,1527,1677,1790,1909,2016,2127,2279,2414,2548,2686,2832,2977,3124,3264,3398,3527,3661,3778,3912,4029,4159,4199,4238,4272,4310,4351,4389,4424,4463,4498,4534,4573,4608,4645,4688,4725,4764,4798,4832,4865,5009,5048,5082,5121,5160,5197,5238,5277,5318,5357,5392,5429,5464,5499,5538,5575,5610,5649,5686,5725,5763,5806,5840,5875,5912,5947,5982,6017,6058,6097,6138,6173,6330,6481],{"id":55,"title":56,"body":57,"description":61,"difficulty":63,"extension":64,"framework":49,"frameworkSlug":47,"meta":65,"navigation":66,"order":12,"path":67,"questions":68,"related":207,"seo":208,"seoDescription":209,"stem":210,"subtopic":211,"topic":212,"topicSlug":213,"updated":214,"__hash__":215},"qa\u002Fjava\u002Fcollections\u002Flist-map-set.md","List Map Set",{"type":58,"value":59,"toc":60},"minimark",[],{"title":61,"searchDepth":22,"depth":22,"links":62},"",[],"medium","md",{},true,"\u002Fjava\u002Fcollections\u002Flist-map-set",[69,74,78,82,87,91,95,99,103,107,111,115,119,123,127,131,135,139,143,147,151,155,159,163,167,171,175,179,183,187,191,195,199,203],{"id":70,"difficulty":71,"q":72,"a":73},"collection-hierarchy","easy","What is the Java Collections Framework?","A unified set of interfaces and implementations for storing groups of objects.\nThe root is `Iterable` -> `Collection`, which branches into:\n\n- **`List`** — ordered, indexed, allows duplicates (`ArrayList`, `LinkedList`).\n- **`Set`** — no duplicates (`HashSet`, `TreeSet`, `LinkedHashSet`).\n- **`Queue`\u002F`Deque`** — ordering for processing (`ArrayDeque`, `PriorityQueue`).\n\n**`Map`** is part of the framework but **not** a `Collection` (it stores\nkey->value pairs, not single elements).\n\n```java\nList\u003CString> list = new ArrayList\u003C>();\nSet\u003CString> set   = new HashSet\u003C>();\nMap\u003CString, Integer> map = new HashMap\u003C>();\n```\n\nProgramming to the interface (`List` not `ArrayList`) lets you swap\nimplementations freely.\n",{"id":75,"difficulty":71,"q":76,"a":77},"list-vs-set-vs-map","What is the difference between List, Set and Map?","- **`List`** — an **ordered, indexed** sequence that **allows duplicates**.\n  Access by position.\n- **`Set`** — an **unordered** collection of **unique** elements (uniqueness\n  defined by `equals`\u002F`hashCode`).\n- **`Map`** — **key->value** pairs with **unique keys**; not a `Collection`.\n\n```java\nList.of(\"a\", \"a\", \"b\");          \u002F\u002F [a, a, b] — duplicates kept\nSet.of(\"a\", \"a\", \"b\");           \u002F\u002F throws — duplicate in Set.of\nnew HashSet\u003C>(List.of(\"a\",\"a\")); \u002F\u002F {a} — duplicate dropped\nMap.of(\"k1\", 1, \"k2\", 2);        \u002F\u002F {k1=1, k2=2}\n```\n\nPick by need: ordered\u002Findexed -> List; uniqueness\u002Fmembership -> Set; lookups by\nkey -> Map.\n",{"id":79,"difficulty":63,"q":80,"a":81},"arraylist-vs-linkedlist","What is the difference between ArrayList and LinkedList?","- **`ArrayList`** — backed by a **resizable array**. O(1) random access by\n  index; O(1) amortized append; O(n) insert\u002Fremove in the middle (shifting).\n  Cache-friendly, lower memory overhead.\n- **`LinkedList`** — a **doubly-linked list**. O(1) insert\u002Fremove at the ends\n  (or at a known node); but O(n) index access (must walk the chain) and higher\n  per-element memory (node pointers).\n\n```java\nList\u003CInteger> a = new ArrayList\u003C>();\na.get(1000);          \u002F\u002F O(1)\nList\u003CInteger> l = new LinkedList\u003C>();\nl.get(1000);          \u002F\u002F O(n) — walks 1000 nodes\n```\n\nIn practice **`ArrayList` wins almost always** — its cache locality beats\n`LinkedList` even for many insert\u002Fremove patterns. Use `LinkedList` mainly as a\n`Deque`\u002Fqueue.\n",{"id":83,"difficulty":84,"q":85,"a":86},"hashmap-internals","hard","How does HashMap work internally?","A `HashMap` is an **array of buckets**. To store a key it computes\n`hashCode()`, spreads the bits, and maps it to a bucket index. Collisions (keys\nlanding in the same bucket) are chained in a **linked list**, which **converts\nto a balanced tree (red-black)** once a bucket exceeds 8 entries (and the table\nis ≥64) — keeping worst-case lookups at O(log n) instead of O(n).\n\n```java\nMap\u003CString, Integer> m = new HashMap\u003C>();\nm.put(\"a\", 1);   \u002F\u002F hash(\"a\") -> bucket -> store entry\nm.get(\"a\");      \u002F\u002F hash(\"a\") -> bucket -> equals() scan -> 1\n```\n\nLookup\u002Finsert are **O(1) average**. When the size exceeds `capacity *\nloadFactor` (default 16 * 0.75 = 12), the table **resizes** (doubles) and\nrehashes. This is why a correct `hashCode`\u002F`equals` pair is essential.\n",{"id":88,"difficulty":84,"q":89,"a":90},"load-factor","What are capacity and load factor in a HashMap?","- **Capacity** — the number of buckets (always a power of two, default 16).\n- **Load factor** — the fullness threshold (default 0.75). When\n  `size > capacity * loadFactor`, the map **resizes** (capacity doubles) and\n  rehashes all entries.\n\n```java\n\u002F\u002F pre-size when you know roughly how many entries to avoid resizes\nMap\u003CString,Integer> m = new HashMap\u003C>(64);\n```\n\nThe 0.75 default trades space vs time: lower load factor = fewer collisions but\nmore memory; higher = denser but slower lookups. Pre-sizing a known-large map\navoids repeated O(n) resizes during population.\n",{"id":92,"difficulty":63,"q":93,"a":94},"hashmap-vs-hashtable","What is the difference between HashMap, Hashtable and ConcurrentHashMap?","- **`HashMap`** — not synchronized, allows **one `null` key** and `null`\n  values, fastest. Use single-threaded or with external synchronization.\n- **`Hashtable`** — legacy, **fully synchronized** (every method locks the whole\n  table), **no `null`** keys\u002Fvalues. Largely obsolete.\n- **`ConcurrentHashMap`** — thread-safe with **fine-grained locking** (per-bin\n  CAS, not a global lock), no `null` keys\u002Fvalues, high concurrency.\n\n```java\nMap\u003CString,Integer> safe = new ConcurrentHashMap\u003C>(); \u002F\u002F modern thread-safe choice\n```\n\nFor concurrent code, prefer **`ConcurrentHashMap`** over `Hashtable` or\n`Collections.synchronizedMap` — it scales far better under contention.\n",{"id":96,"difficulty":63,"q":97,"a":98},"hashset-treeset-linkedhashset","What is the difference between HashSet, LinkedHashSet and TreeSet?","- **`HashSet`** — backed by a `HashMap`; **no ordering**, O(1) add\u002Fcontains.\n- **`LinkedHashSet`** — `HashSet` + a linked list, so it preserves\n  **insertion order**; O(1) with slightly more memory.\n- **`TreeSet`** — a red-black tree; keeps elements in **sorted order**, O(log n)\n  operations, requires `Comparable`\u002F`Comparator`.\n\n```java\nnew HashSet\u003C>(List.of(3,1,2));       \u002F\u002F order undefined, e.g. [1,2,3] or other\nnew LinkedHashSet\u003C>(List.of(3,1,2)); \u002F\u002F [3, 1, 2] — insertion order\nnew TreeSet\u003C>(List.of(3,1,2));       \u002F\u002F [1, 2, 3] — sorted\n```\n\nChoose by requirement: speed -> HashSet; remember order -> LinkedHashSet; sorted\u002F\nrange queries -> TreeSet.\n",{"id":100,"difficulty":63,"q":101,"a":102},"hashmap-treemap-linkedhashmap","How do HashMap, LinkedHashMap and TreeMap differ?","They mirror the Set variants:\n\n- **`HashMap`** — no order, O(1) average.\n- **`LinkedHashMap`** — insertion order (or access order, enabling easy LRU\n  caches), O(1).\n- **`TreeMap`** — keys sorted, O(log n), supports range\u002Fnavigation methods\n  (`firstKey`, `ceilingKey`, `subMap`).\n\n```java\n\u002F\u002F LinkedHashMap as an LRU cache\nvar lru = new LinkedHashMap\u003CString,Integer>(16, 0.75f, true) {\n  protected boolean removeEldestEntry(Map.Entry\u003CString,Integer> e) {\n    return size() > 100;\n  }\n};\n```\n\n`TreeMap`'s navigation API is its superpower; `LinkedHashMap`'s access-order\nmode is the classic LRU trick.\n",{"id":104,"difficulty":84,"q":105,"a":106},"fail-fast","What is a fail-fast iterator and ConcurrentModificationException?","Most collection iterators are **fail-fast**: they track a `modCount`, and if the\ncollection is structurally modified during iteration (other than through the\niterator's own `remove`), they throw **`ConcurrentModificationException`** —\nfailing immediately rather than risking corrupt results.\n\n```java\nfor (String s : list) {\n  if (s.isEmpty()) list.remove(s); \u002F\u002F ConcurrentModificationException\n}\n\nIterator\u003CString> it = list.iterator();\nwhile (it.hasNext()) {\n  if (it.next().isEmpty()) it.remove(); \u002F\u002F safe via the iterator\n}\nlist.removeIf(String::isEmpty);          \u002F\u002F cleanest\n```\n\nFail-fast is **best-effort** (not guaranteed). Concurrent collections like\n`CopyOnWriteArrayList`\u002F`ConcurrentHashMap` are **fail-safe** instead — they\niterate over a snapshot and don't throw.\n",{"id":108,"difficulty":63,"q":109,"a":110},"comparable-vs-comparator","What is the difference between Comparable and Comparator?","- **`Comparable\u003CT>`** — the type's **natural ordering**, implemented *by the\n  class itself* via `compareTo`. One ordering per class.\n- **`Comparator\u003CT>`** — an **external** ordering object via `compare`, so you can\n  define many orderings without touching the class.\n\n```java\nclass User implements Comparable\u003CUser> {\n  int age; String name;\n  public int compareTo(User o) { return Integer.compare(age, o.age); } \u002F\u002F natural\n}\n\u002F\u002F alternate orderings without modifying User:\nusers.sort(Comparator.comparing(u -> u.name));\nusers.sort(Comparator.comparingInt((User u) -> u.age).reversed()\n                     .thenComparing(u -> u.name));\n```\n\nRule of thumb: one obvious default ordering -> `Comparable`; multiple\u002Fcontextual\norderings -> `Comparator` (which also composes nicely with `thenComparing`).\n",{"id":112,"difficulty":63,"q":113,"a":114},"iterator-vs-listiterator","What is the difference between Iterator and ListIterator?","- **`Iterator`** — forward-only traversal of any `Collection`; supports\n  `hasNext`, `next`, and `remove`.\n- **`ListIterator`** — a `List`-only iterator that goes **both directions**\n  (`hasPrevious`\u002F`previous`), exposes indices (`nextIndex`), and can **`add`**\n  and **`set`** elements during iteration.\n\n```java\nListIterator\u003CString> it = list.listIterator();\nwhile (it.hasNext()) {\n  String s = it.next();\n  if (s.isBlank()) it.set(\"(empty)\"); \u002F\u002F replace in place\n}\n```\n\nUse `ListIterator` when you need to walk backward or modify elements while\niterating a list.\n",{"id":116,"difficulty":63,"q":117,"a":118},"arraylist-resize","How does ArrayList grow, and what is amortized O(1)?","An `ArrayList` holds an internal array. When it fills up, it allocates a **larger\narray** (~1.5×) and copies the elements over — an O(n) operation. But because\ngrowth happens **rarely** (geometrically), the *average* cost of `add` over many\ncalls is **O(1) amortized**.\n\n```java\nList\u003CInteger> list = new ArrayList\u003C>(1000); \u002F\u002F pre-size: skip the resizes\nfor (int i = 0; i \u003C 1000; i++) list.add(i);\n```\n\nIf you know the final size, pass an **initial capacity** to avoid the repeated\ncopies. Note `size()` (number of elements) differs from the internal capacity.\n",{"id":120,"difficulty":71,"q":121,"a":122},"generics-why","Why are generics used in collections?","Generics give collections **compile-time type safety** and remove casts. Before\ngenerics, collections held `Object`, so you could insert anything and had to cast\non the way out — risking `ClassCastException` at runtime.\n\n```java\nList\u003CString> names = new ArrayList\u003C>();\nnames.add(\"Ada\");\nString s = names.get(0);   \u002F\u002F no cast; adding an Integer won't compile\n\nList raw = new ArrayList(); \u002F\u002F raw type — unsafe, avoid\nraw.add(42);\nString bad = (String) raw.get(0); \u002F\u002F compiles, ClassCastException at runtime\n```\n\nGenerics catch type errors at **compile time** and make code self-documenting.\n",{"id":124,"difficulty":84,"q":125,"a":126},"type-erasure","What is type erasure?","Java generics are a **compile-time** feature. After type checking, the compiler\n**erases** type parameters — `List\u003CString>` and `List\u003CInteger>` both become raw\n`List` at runtime, with casts inserted automatically. This keeps backward\ncompatibility with pre-generics code.\n\n```java\nList\u003CString> a = new ArrayList\u003C>();\nList\u003CInteger> b = new ArrayList\u003C>();\na.getClass() == b.getClass();  \u002F\u002F true — same runtime class\n\n\u002F\u002F consequences of erasure:\n\u002F\u002F new T[]      -> illegal\n\u002F\u002F x instanceof List\u003CString> -> illegal (only List\u003C?>)\n```\n\nErasure is why you can't do `new T()`, create generic arrays, or check a generic\ntype with `instanceof` — the type info simply isn't there at runtime.\n",{"id":128,"difficulty":84,"q":129,"a":130},"wildcards","What do the ? extends and ? super wildcards mean (PECS)?","Bounded wildcards control what you can read\u002Fwrite through a generic reference:\n\n- **`? extends T`** — an unknown subtype of T; you can **read** Ts out, but\n  **can't add** (the exact type is unknown). A **Producer**.\n- **`? super T`** — an unknown supertype of T; you can **add** Ts, but reads come\n  back as `Object`. A **Consumer**.\n\nThe mnemonic is **PECS — Producer `extends`, Consumer `super`**:\n\n```java\nvoid copy(List\u003C? extends Number> src, List\u003C? super Number> dst) {\n  for (Number n : src) dst.add(n); \u002F\u002F read from producer, write to consumer\n}\n```\n\n`src` produces values (read-only), `dst` consumes them (write-ok). This is how\n`Collections.copy` and friends are typed.\n",{"id":132,"difficulty":63,"q":133,"a":134},"queue-deque","What are Queue and Deque, and which implementations are common?","- **`Queue`** — FIFO processing; `offer`\u002F`poll`\u002F`peek`. `PriorityQueue` orders\n  by priority instead of arrival.\n- **`Deque`** (\"deck\") — double-ended queue; add\u002Fremove at **both ends**. Works\n  as a queue **or** a stack.\n\n```java\nDeque\u003CInteger> stack = new ArrayDeque\u003C>();\nstack.push(1); stack.push(2); stack.pop();  \u002F\u002F LIFO -> 2\n\nQueue\u003CInteger> q = new ArrayDeque\u003C>();\nq.offer(1); q.offer(2); q.poll();           \u002F\u002F FIFO -> 1\n\nQueue\u003CInteger> pq = new PriorityQueue\u003C>();\npq.offer(5); pq.offer(1); pq.peek();        \u002F\u002F 1 (smallest first)\n```\n\nPrefer **`ArrayDeque`** over the legacy `Stack` class (synchronized, extends\n`Vector`) for stack\u002Fqueue needs.\n",{"id":136,"difficulty":63,"q":137,"a":138},"immutable-collections","How do you create immutable collections?","- **`List.of` \u002F `Set.of` \u002F `Map.of`** (Java 9+) — concise, truly immutable,\n  reject `null` and (for Set\u002FMap) duplicates.\n- **`Collections.unmodifiableList(...)`** — an unmodifiable *view* over an\n  existing collection.\n- **`List.copyOf(...)`** — an immutable copy of any collection.\n\n```java\nList\u003CString> a = List.of(\"x\", \"y\");        \u002F\u002F immutable\na.add(\"z\");                                 \u002F\u002F UnsupportedOperationException\n\nList\u003CString> backing = new ArrayList\u003C>(List.of(\"x\"));\nList\u003CString> view = Collections.unmodifiableList(backing);\nbacking.add(\"y\");                           \u002F\u002F view reflects this — it's a VIEW\n```\n\nGotcha: `unmodifiableList` is a **view** — mutating the backing list still shows\nthrough it. `List.of`\u002F`copyOf` are genuinely independent and immutable.\n",{"id":140,"difficulty":63,"q":141,"a":142},"null-handling","Which collections allow null and which do not?","- **`HashMap`** — one `null` key, many `null` values. **`HashSet`** — one\n  `null` element. `ArrayList`\u002F`LinkedList` allow `null`s.\n- **`Hashtable`, `ConcurrentHashMap`, `TreeMap` (keys)** — **no `null`** (TreeMap\n  can't compare null; concurrent maps disallow it to avoid ambiguity).\n- **`List.of`\u002F`Set.of`\u002F`Map.of`** — reject `null` entirely.\n\n```java\nnew HashMap\u003C>().put(null, 1);          \u002F\u002F\nnew ConcurrentHashMap\u003C>().put(null,1); \u002F\u002F NullPointerException\nList.of(\"a\", null);                    \u002F\u002F NullPointerException\n```\n\nAvoiding `null` (using `Optional` or sentinel objects) sidesteps a whole class\nof these errors.\n",{"id":144,"difficulty":71,"q":145,"a":146},"collections-utility","What does the Collections utility class provide?","`java.util.Collections` is a toolbox of static helpers that operate on\ncollections: `sort`, `reverse`, `shuffle`, `min`\u002F`max`, `binarySearch`,\n`frequency`, `unmodifiableXxx`, `synchronizedXxx`, and `emptyList()`\u002F\n`singletonList()`.\n\n```java\nList\u003CInteger> nums = new ArrayList\u003C>(List.of(3, 1, 2));\nCollections.sort(nums);                 \u002F\u002F [1, 2, 3]\nCollections.reverse(nums);              \u002F\u002F [3, 2, 1]\nint max = Collections.max(nums);        \u002F\u002F 3\n```\n\nDon't confuse `Collections` (utility class, plural) with `Collection` (the\ninterface). `Arrays` is its array-focused sibling (`Arrays.sort`,\n`Arrays.asList`).\n",{"id":148,"difficulty":84,"q":149,"a":150},"arrays-aslist","What are the pitfalls of Arrays.asList()?","`Arrays.asList` returns a **fixed-size list backed by the array** — not a normal\n`ArrayList`. You can `set` elements (it writes through to the array) but **can't\n`add`\u002F`remove`** (throws `UnsupportedOperationException`).\n\n```java\nList\u003CInteger> l = Arrays.asList(1, 2, 3);\nl.set(0, 9);   \u002F\u002F writes through to the backing array\nl.add(4);      \u002F\u002F UnsupportedOperationException\n\n\u002F\u002F also: a primitive array gives a 1-element List\u003Cint[]>, not List\u003CInteger>!\nList\u003Cint[]> oops = Arrays.asList(new int[]{1, 2, 3}); \u002F\u002F size 1\n\nList\u003CInteger> real = new ArrayList\u003C>(Arrays.asList(1, 2, 3)); \u002F\u002F mutable copy\n```\n\nWrap it in `new ArrayList\u003C>(...)` for a fully mutable list, and remember\nautoboxing: pass `Integer[]`, not `int[]`.\n",{"id":152,"difficulty":63,"q":153,"a":154},"set-uniqueness","How does a HashSet decide that two elements are duplicates?","A `HashSet` (backed by a `HashMap`) treats two elements as duplicates when their\n**`hashCode()` matches** *and* **`equals()` returns true**. So uniqueness depends\nentirely on a correct `equals`\u002F`hashCode` implementation.\n\n```java\nclass P { int x;\n  \u002F\u002F no equals\u002FhashCode -> identity-based, \"duplicates\" stay\n}\nSet\u003CP> s = new HashSet\u003C>();\ns.add(new P()); s.add(new P());  \u002F\u002F size 2 (different objects)\n```\n\nIf you forget to override them, two logically-equal objects are treated as\ndistinct. If you override `equals` but not `hashCode` (or vice versa), the set\nmay store duplicates or fail to find elements.\n",{"id":156,"difficulty":84,"q":157,"a":158},"mutable-key","What happens if you use a mutable object as a HashMap key?","The map places the key in a bucket based on its **hash at insertion time**. If\nyou then **mutate the key** so its `hashCode` changes, it ends up in the \"wrong\"\nbucket — the map can no longer find it, even with the same reference.\n\n```java\nMap\u003CList\u003CInteger>, String> m = new HashMap\u003C>();\nList\u003CInteger> key = new ArrayList\u003C>(List.of(1));\nm.put(key, \"v\");\nkey.add(2);                 \u002F\u002F mutates the key -> hashCode changes\nm.get(key);                 \u002F\u002F null! lost in the wrong bucket\n```\n\nRule: **use immutable keys** (`String`, `Integer`, records, frozen value\nobjects). It's the same reason Python forbids list keys.\n",{"id":160,"difficulty":63,"q":161,"a":162},"concurrent-modification-map","How do you safely remove entries from a Map while iterating?","Don't call `map.remove` inside an enhanced-for over its entries — that throws\n`ConcurrentModificationException`. Use the **iterator's `remove`**, or the\ncleaner `removeIf`\u002F`entrySet().removeIf`, or `keySet`\u002F`values` views.\n\n```java\n\u002F\u002F iterator\nIterator\u003CMap.Entry\u003CString,Integer>> it = map.entrySet().iterator();\nwhile (it.hasNext()) {\n  if (it.next().getValue() == 0) it.remove();\n}\n\u002F\u002F concise\nmap.values().removeIf(v -> v == 0);\nmap.entrySet().removeIf(e -> e.getValue() == 0);\n```\n\nFor concurrent access from multiple threads, use `ConcurrentHashMap`, whose\niterators are fail-safe.\n",{"id":164,"difficulty":63,"q":165,"a":166},"stack-vector","Why are Vector and Stack discouraged?","`Vector` and its subclass `Stack` are **legacy synchronized** collections from\nJava 1.0. Every method is synchronized, so they pay locking overhead even in\nsingle-threaded code, and that per-method locking doesn't make *compound*\noperations atomic anyway.\n\n```java\nDeque\u003CInteger> stack = new ArrayDeque\u003C>(); \u002F\u002F modern stack\nList\u003CInteger> list = new ArrayList\u003C>();    \u002F\u002F modern list\n```\n\nUse `ArrayList` (unsynchronized list), `ArrayDeque` (stack\u002Fqueue), and pick a\n*concurrent* collection or explicit synchronization when you genuinely need\nthread safety — not `Vector`\u002F`Stack`.\n",{"id":168,"difficulty":63,"q":169,"a":170},"map-getordefault-merge","What do getOrDefault, computeIfAbsent and merge do?","Java 8 added convenience methods that simplify common map idioms:\n\n- **`getOrDefault(k, d)`** — value for `k`, or `d` if absent.\n- **`computeIfAbsent(k, fn)`** — compute and store a value only if `k` is\n  missing; perfect for multimaps.\n- **`merge(k, v, fn)`** — combine an existing value with a new one; perfect for\n  counting.\n\n```java\n\u002F\u002F grouping (multimap)\nmap.computeIfAbsent(key, k -> new ArrayList\u003C>()).add(item);\n\n\u002F\u002F frequency count\ncounts.merge(word, 1, Integer::sum);\n\nint n = counts.getOrDefault(\"x\", 0);\n```\n\nThese replace verbose `if (map.containsKey(...)) ... else ...` blocks and are\natomic on `ConcurrentHashMap`.\n",{"id":172,"difficulty":63,"q":173,"a":174},"priorityqueue","How does a PriorityQueue work?","A `PriorityQueue` is a **binary heap** that always dequeues the **highest-\npriority** element (by natural order or a `Comparator`), not FIFO. `offer`\u002F`poll`\nare O(log n); `peek` is O(1).\n\n```java\n\u002F\u002F min-heap (default): smallest first\nQueue\u003CInteger> min = new PriorityQueue\u003C>();\n\u002F\u002F max-heap: reverse the comparator\nQueue\u003CInteger> max = new PriorityQueue\u003C>(Comparator.reverseOrder());\nmax.offer(1); max.offer(5); max.peek(); \u002F\u002F 5\n```\n\nCaveat: it's only ordered at the **head** — iterating it does *not* yield sorted\norder. It's the go-to for \"top-K\", Dijkstra, and scheduling problems.\n",{"id":176,"difficulty":63,"q":177,"a":178},"synchronized-collections","What is the difference between synchronized and concurrent collections?","- **`Collections.synchronizedList\u002FMap(...)`** — wraps a collection so each method\n  locks the **whole object**. Simple, but compound operations\n  (check-then-act, iteration) still need external synchronization, and there's\n  no concurrency.\n- **Concurrent collections** (`ConcurrentHashMap`, `CopyOnWriteArrayList`,\n  `ConcurrentLinkedQueue`) — designed for concurrency with fine-grained or\n  lock-free strategies; far better throughput.\n\n```java\nList\u003CInteger> s = Collections.synchronizedList(new ArrayList\u003C>());\nsynchronized (s) {                 \u002F\u002F still must lock to iterate safely\n  for (int x : s) { }\n}\nMap\u003CString,Integer> c = new ConcurrentHashMap\u003C>(); \u002F\u002F no external lock needed\n```\n\nPrefer the concurrent collections in new code.\n",{"id":180,"difficulty":84,"q":181,"a":182},"copyonwrite","When would you use CopyOnWriteArrayList?","`CopyOnWriteArrayList` makes a fresh copy of the backing array on **every\nmutation**, so reads and iteration are **lock-free and never throw\n`ConcurrentModificationException`** (iterators see a stable snapshot). The cost:\nwrites are O(n).\n\n```java\nList\u003CListener> listeners = new CopyOnWriteArrayList\u003C>();\nfor (Listener l : listeners) l.onEvent(); \u002F\u002F safe even if another thread adds\n```\n\nIdeal for **read-mostly, write-rarely** scenarios with concurrent iteration —\nclassically event-listener lists. Terrible for write-heavy workloads.\n",{"id":184,"difficulty":63,"q":185,"a":186},"equals-in-collections","Why must equals and hashCode be consistent for collections to work?","Hash-based collections (`HashMap`, `HashSet`) locate elements by **hash first,\nthen `equals`**. If two equal objects have different hash codes, they land in\ndifferent buckets and the collection can't recognize them as the same — you get\nduplicates in a Set or failed lookups in a Map.\n\n```java\nclass Key {\n  int id;\n  Key(int id) { this.id = id; }\n  @Override public boolean equals(Object o) {\n    return o instanceof Key k && k.id == id;\n  }\n  \u002F\u002F forgot hashCode -> equal Keys get different hashes\n}\nMap\u003CKey,String> m = new HashMap\u003C>();\nm.put(new Key(1), \"a\");\nm.get(new Key(1));   \u002F\u002F null — wrong bucket\n```\n\nAlways override **both together**, keeping them based on the same fields.\n",{"id":188,"difficulty":84,"q":189,"a":190},"tree-navigation","What navigation methods do TreeMap and TreeSet provide?","Because they're sorted, `TreeMap`\u002F`TreeSet` (the `NavigableMap`\u002F`NavigableSet`\ninterfaces) offer **range and neighbor queries** that hash structures can't:\n\n- `first()\u002Flast()`, `floor(x)` (≤ x), `ceiling(x)` (≥ x), `lower(x)` (\u003C x),\n  `higher(x)` (> x).\n- `headSet`, `tailSet`, `subSet` \u002F `headMap`, `tailMap`, `subMap` for ranges.\n\n```java\nNavigableSet\u003CInteger> s = new TreeSet\u003C>(List.of(10, 20, 30));\ns.floor(25);    \u002F\u002F 20  (largest ≤ 25)\ns.ceiling(25);  \u002F\u002F 30  (smallest ≥ 25)\ns.subSet(15, 35); \u002F\u002F [20, 30]\n```\n\nThese make `TreeMap`\u002F`TreeSet` the choice for \"nearest value\", ranges, and\nordered iteration — at O(log n) per operation.\n",{"id":192,"difficulty":63,"q":193,"a":194},"enumset-enummap","What are EnumSet and EnumMap and why use them?","Specialized, highly efficient collections for **enum** keys\u002Felements.\n`EnumSet` is internally a **bit vector**; `EnumMap` is backed by a **plain\narray** indexed by `ordinal()`. Both are much faster and smaller than\n`HashSet`\u002F`HashMap` for enums, and iterate in **enum declaration order**.\n\n```java\nenum Day { MON, TUE, WED, THU, FRI, SAT, SUN }\nEnumSet\u003CDay> weekend = EnumSet.of(Day.SAT, Day.SUN);\nEnumMap\u003CDay, String> plans = new EnumMap\u003C>(Day.class);\nplans.put(Day.MON, \"gym\");\n```\n\nWhenever your keys are enum constants, prefer these over the general-purpose\ncollections.\n",{"id":196,"difficulty":63,"q":197,"a":198},"stream-collectors","How do you build collections from a Stream?","Terminal `collect` with the `Collectors` factory turns a stream into a\ncollection or grouped structure:\n\n```java\nList\u003CString> upper = names.stream()\n    .map(String::toUpperCase)\n    .collect(Collectors.toList());        \u002F\u002F or .toList() (Java 16+)\n\nMap\u003CBoolean, List\u003CInteger>> parts = nums.stream()\n    .collect(Collectors.partitioningBy(n -> n % 2 == 0));\n\nMap\u003CDept, List\u003CEmp>> byDept = emps.stream()\n    .collect(Collectors.groupingBy(Emp::dept));\n```\n\n`Collectors` covers `toSet`, `toMap`, `groupingBy`, `partitioningBy`,\n`joining`, and `counting` — declarative replacements for manual loop-and-add.\n",{"id":200,"difficulty":84,"q":201,"a":202},"list-remove-int-trap","What is the trap with List.remove and an int argument?","`List` has two overloads: `remove(int index)` removes **by position**, and\n`remove(Object o)` removes **by value**. With a `List\u003CInteger>`, passing a\nprimitive `int` calls the **index** version — not the value one.\n\n```java\nList\u003CInteger> list = new ArrayList\u003C>(List.of(10, 20, 30));\nlist.remove(1);                 \u002F\u002F removes INDEX 1 -> [10, 30]\nlist.remove(Integer.valueOf(10)); \u002F\u002F removes the VALUE 10 -> [30]\n```\n\nTo remove a value, box it explicitly with `Integer.valueOf(x)` (or cast to\n`(Integer)`). This is one of the most common surprise bugs with integer lists.\n",{"id":204,"difficulty":71,"q":205,"a":206},"choosing-collection","How do you choose the right collection for a task?","Match the data structure to the dominant operation:\n\n- Ordered list, index access, mostly appends -> **`ArrayList`**.\n- Unique elements, fast membership tests -> **`HashSet`**.\n- Key->value lookups -> **`HashMap`**.\n- Need sorted order or range queries -> **`TreeMap`\u002F`TreeSet`**.\n- Preserve insertion order -> **`LinkedHashMap`\u002F`LinkedHashSet`**.\n- FIFO queue \u002F stack -> **`ArrayDeque`**; priority -> **`PriorityQueue`**.\n- Concurrent access -> **`ConcurrentHashMap`**, `CopyOnWriteArrayList`.\n\n```java\nMap\u003CString,Integer> wordCount = new HashMap\u003C>();   \u002F\u002F counting\nSet\u003CString> seen = new HashSet\u003C>();                \u002F\u002F dedupe\n```\n\nStart from the access pattern (lookup? order? uniqueness? concurrency?) and the\nchoice usually falls out.\n",null,{"description":61},"Java Collections Framework interview questions — List vs Set vs Map, ArrayList vs LinkedList, HashMap internals, fail-fast iterators, Comparable vs Comparator, generics and immutable collections.","java\u002Fcollections\u002Flist-map-set","Lists, Maps & Sets","Collections","collections","2026-06-18","4nQd1Mi8XVoUVUsO5rEz9BXEiWRC6sSMJZ0skAAkT9g",{"id":217,"title":218,"body":219,"description":61,"difficulty":84,"extension":64,"framework":49,"frameworkSlug":47,"meta":223,"navigation":66,"order":12,"path":224,"questions":225,"related":207,"seo":366,"seoDescription":367,"stem":368,"subtopic":369,"topic":370,"topicSlug":371,"updated":214,"__hash__":372},"qa\u002Fjava\u002Fconcurrency\u002Fthreads.md","Threads",{"type":58,"value":220,"toc":221},[],{"title":61,"searchDepth":22,"depth":22,"links":222},[],{},"\u002Fjava\u002Fconcurrency\u002Fthreads",[226,230,234,238,242,246,250,254,258,262,266,270,274,278,282,286,290,294,298,302,306,310,314,318,322,326,330,334,338,342,346,350,354,358,362],{"id":227,"difficulty":71,"q":228,"a":229},"thread-vs-runnable","What are the ways to create a thread in Java?","Two basic approaches, plus the modern preferred one:\n\n- **Extend `Thread`** and override `run()` — simple, but uses up your single\n  inheritance slot.\n- **Implement `Runnable`** and pass it to a `Thread` — favored, because it\n  separates the task from the thread and works with executors.\n\n```java\n\u002F\u002F Runnable (preferred)\nRunnable task = () -> System.out.println(\"working\");\nnew Thread(task).start();\n\n\u002F\u002F extending Thread\nclass Worker extends Thread { public void run() { } }\n```\n\nIn real code you rarely create threads directly at all — you submit\n`Runnable`\u002F`Callable` tasks to an **`ExecutorService`**, which manages a pool\nfor you.\n",{"id":231,"difficulty":71,"q":232,"a":233},"start-vs-run","What is the difference between start() and run()?","**`start()`** asks the JVM to create a **new thread** and invoke `run()` on it —\nconcurrent execution. Calling **`run()`** directly just executes the method on\nthe **current** thread, like any ordinary call — no concurrency at all.\n\n```java\nThread t = new Thread(() -> System.out.println(Thread.currentThread().getName()));\nt.start();   \u002F\u002F prints \"Thread-0\" — runs on a new thread\nt.run();     \u002F\u002F prints \"main\"    — runs on the caller's thread\n```\n\nAlso, calling `start()` **twice** on the same `Thread` throws\n`IllegalThreadStateException` — a thread can be started only once.\n",{"id":235,"difficulty":63,"q":236,"a":237},"thread-lifecycle","What are the states in a thread's lifecycle?","A `Thread` moves through these `Thread.State` values:\n\n- **NEW** — created but not started.\n- **RUNNABLE** — eligible to run (running or waiting for CPU).\n- **BLOCKED** — waiting to acquire a monitor lock.\n- **WAITING** — waiting indefinitely (`wait()`, `join()`, `park()`).\n- **TIMED_WAITING** — waiting with a timeout (`sleep`, `wait(ms)`).\n- **TERMINATED** — finished or threw.\n\n```java\nThread t = new Thread(task);\nt.getState();  \u002F\u002F NEW\nt.start();\nt.getState();  \u002F\u002F RUNNABLE\n```\n\nTransitions are driven by the scheduler and synchronization calls; you observe\n(not directly set) the state.\n",{"id":239,"difficulty":63,"q":240,"a":241},"race-condition","What is a race condition?","A race condition occurs when **multiple threads access shared mutable state\nconcurrently** and the outcome depends on the **timing** of their interleaving.\nOperations that look atomic (like `count++`) are actually read-modify-write\nsequences that can interleave and lose updates.\n\n```java\nclass Counter {\n  int count;\n  void inc() { count++; } \u002F\u002F read, +1, write — NOT atomic\n}\n\u002F\u002F 1000 threads each calling inc() once -> final count often \u003C 1000\n```\n\nFixes: make the operation atomic (`synchronized`, `AtomicInteger`), or avoid\nshared mutable state. Race conditions are insidious because they're\n**intermittent** and timing-dependent.\n",{"id":243,"difficulty":63,"q":244,"a":245},"synchronized","What does the synchronized keyword do?","`synchronized` enforces **mutual exclusion**: only one thread can hold an\nobject's **monitor lock** at a time, so synchronized code runs serially. It also\nestablishes a **happens-before** relationship, guaranteeing memory visibility of\nchanges made under the lock.\n\n```java\nclass Counter {\n  private int count;\n  synchronized void inc() { count++; }      \u002F\u002F locks on `this`\n  void dec() {\n    synchronized (this) { count--; }        \u002F\u002F synchronized block\n  }\n}\n```\n\nA `synchronized` instance method locks on `this`; a `synchronized` static method\nlocks on the **`Class`** object. Keep critical sections small to limit\ncontention.\n",{"id":247,"difficulty":84,"q":248,"a":249},"volatile","What does volatile do and what does it not do?","`volatile` guarantees **visibility** and **ordering**: writes by one thread are\nimmediately visible to others (no per-thread caching), and it prevents\nreordering around the access. What it does **not** provide is **atomicity** for\ncompound operations.\n\n```java\nvolatile boolean running = true;  \u002F\u002F flag — visibility is enough\nvoid stop() { running = false; }  \u002F\u002F other threads see this promptly\n\nvolatile int count;\ncount++;   \u002F\u002F still a race — read-modify-write isn't atomic\n```\n\nUse `volatile` for **flags\u002Fstate published once** (the classic stop-flag), and\n`synchronized`\u002F`Atomic*` when you need atomic compound updates.\n",{"id":251,"difficulty":84,"q":252,"a":253},"synchronized-vs-volatile","What is the difference between synchronized and volatile?","- **`volatile`** — only **visibility + ordering** for a single variable. No\n  locking, no atomicity for compound ops. Cheap.\n- **`synchronized`** — **mutual exclusion + visibility**. Makes whole code\n  blocks atomic, can guard multiple variables, but threads can block on the\n  lock.\n\n```java\nvolatile boolean flag;       \u002F\u002F visibility only\nsynchronized void transfer() {  \u002F\u002F atomicity across several fields\n  from -= amt; to += amt;\n}\n```\n\nQuick rule: a single flag\u002Freference written-then-read -> `volatile`; a\nmulti-step invariant or counter -> `synchronized` (or an atomic\u002Flock).\n",{"id":255,"difficulty":84,"q":256,"a":257},"deadlock","What is a deadlock and how do you prevent it?","A deadlock is two+ threads each **holding a lock the other needs**, so all wait\nforever. It requires four conditions (Coffman): mutual exclusion, hold-and-wait,\nno preemption, and circular wait.\n\n```java\n\u002F\u002F Thread 1: lock A then B   |   Thread 2: lock B then A  -> deadlock\nsynchronized (a) { synchronized (b) { } }\nsynchronized (b) { synchronized (a) { } }\n```\n\nPrevention: acquire locks in a **consistent global order**, use **timeouts**\n(`tryLock`), reduce lock scope, or avoid multiple locks entirely. Breaking any\none Coffman condition (usually circular wait, via lock ordering) prevents\ndeadlock.\n",{"id":259,"difficulty":84,"q":260,"a":261},"livelock-starvation","What are livelock and starvation?","- **Starvation** — a thread is perpetually denied the resources\u002FCPU it needs\n  (e.g. low-priority threads, or always losing a lock to greedier ones), so it\n  never makes progress.\n- **Livelock** — threads are **actively running** but keep responding to each\n  other in a way that prevents progress (like two people stepping aside in the\n  same direction repeatedly).\n\n```java\n\u002F\u002F livelock sketch: both threads keep \"politely\" backing off\nwhile (other.isActive()) { backOff(); \u002F* never proceeds *\u002F }\n```\n\nUnlike deadlock (threads blocked), livelocked threads consume CPU. Fixes\ninclude randomized back-off, fairness policies, and bounded retries.\n",{"id":263,"difficulty":84,"q":264,"a":265},"wait-notify","How do wait(), notify() and notifyAll() work?","They coordinate threads on an object's monitor and **must be called while\nholding that object's lock** (inside `synchronized`). `wait()` releases the lock\nand suspends the thread until notified; `notify()` wakes one waiter,\n`notifyAll()` wakes all.\n\n```java\nsynchronized (queue) {\n  while (queue.isEmpty()) {   \u002F\u002F ALWAYS loop, never a bare if\n    queue.wait();             \u002F\u002F releases lock, waits\n  }\n  process(queue.remove());\n}\n\u002F\u002F producer:\nsynchronized (queue) { queue.add(item); queue.notifyAll(); }\n```\n\nAlways re-check the condition in a **`while`** loop (spurious wakeups + stale\nconditions). Prefer `notifyAll` unless you're certain one waiter suffices.\n",{"id":267,"difficulty":63,"q":268,"a":269},"sleep-vs-wait","What is the difference between sleep() and wait()?","- **`Thread.sleep(ms)`** — a static method that pauses the **current** thread\n  for a time **without releasing any locks** it holds. For timing\u002Fthrottling.\n- **`Object.wait()`** — an instance method that **releases the object's lock**\n  and waits to be notified; must be called inside `synchronized`. For\n  coordination between threads.\n\n```java\nsynchronized (lock) {\n  Thread.sleep(100);  \u002F\u002F keeps holding `lock` the whole time\n  lock.wait();        \u002F\u002F releases `lock` while waiting\n}\n```\n\nKey distinction: `sleep` keeps the lock, `wait` gives it up. Using `sleep` for\ninter-thread coordination is a classic anti-pattern.\n",{"id":271,"difficulty":63,"q":272,"a":273},"executor-service","What is an ExecutorService and why use a thread pool?","An `ExecutorService` manages a **pool of reusable threads** and a task queue, so\nyou submit work instead of creating threads by hand. This caps the thread count,\nreuses threads (avoiding creation overhead), and decouples task submission from\nexecution.\n\n```java\nExecutorService pool = Executors.newFixedThreadPool(4);\nFuture\u003CInteger> f = pool.submit(() -> compute());\npool.execute(() -> fireAndForget());\npool.shutdown();                 \u002F\u002F stop accepting; finish queued tasks\npool.awaitTermination(1, TimeUnit.MINUTES);\n```\n\nCreating a thread per task doesn't scale — unbounded threads exhaust memory and\nthrash the scheduler. Always `shutdown()` a pool to release its threads.\n",{"id":275,"difficulty":63,"q":276,"a":277},"thread-pool-types","What thread pool types does Executors provide?","- **`newFixedThreadPool(n)`** — fixed number of threads, unbounded queue.\n- **`newCachedThreadPool()`** — grows\u002Fshrinks on demand; reuses idle threads.\n- **`newSingleThreadExecutor()`** — one thread, sequential task processing.\n- **`newScheduledThreadPool(n)`** — for delayed\u002Fperiodic tasks.\n- **`newVirtualThreadPerTaskExecutor()`** (Java 21) — a virtual thread per task.\n\n```java\nvar scheduled = Executors.newScheduledThreadPool(2);\nscheduled.scheduleAtFixedRate(this::poll, 0, 5, TimeUnit.SECONDS);\n```\n\nIn production many teams construct **`ThreadPoolExecutor`** directly to control\nthe queue bounds and rejection policy, since `newFixedThreadPool`'s unbounded\nqueue can hide backpressure problems.\n",{"id":279,"difficulty":63,"q":280,"a":281},"callable-future","What is the difference between Runnable and Callable, and what is a Future?","- **`Runnable`** — `run()` returns **nothing** and can't throw checked\n  exceptions.\n- **`Callable\u003CV>`** — `call()` **returns a value** and may throw checked\n  exceptions.\n- **`Future\u003CV>`** — a handle to a pending result; `get()` blocks until it's\n  ready, `isDone()`\u002F`cancel()` manage it.\n\n```java\nCallable\u003CInteger> task = () -> 6 * 7;\nFuture\u003CInteger> f = pool.submit(task);\nInteger result = f.get();   \u002F\u002F blocks until done -> 42\n```\n\n`Future.get()` is **blocking**, which is its main weakness — addressed by\n`CompletableFuture`'s non-blocking composition.\n",{"id":283,"difficulty":84,"q":284,"a":285},"completablefuture","What is CompletableFuture and how does it improve on Future?","`CompletableFuture` is a `Future` you can **compose and chain\nasynchronously** — attaching callbacks instead of blocking on `get()`, and\ncombining multiple async results.\n\n```java\nCompletableFuture.supplyAsync(() -> fetchUser(id))\n    .thenApply(User::name)                 \u002F\u002F transform when ready\n    .thenCompose(name -> lookupAsync(name)) \u002F\u002F chain another async call\n    .exceptionally(ex -> \"fallback\")        \u002F\u002F handle errors\n    .thenAccept(System.out::println);       \u002F\u002F consume, non-blocking\n\nCompletableFuture.allOf(f1, f2, f3).join();  \u002F\u002F wait for several\n```\n\nIt enables a non-blocking pipeline (`thenApply`\u002F`thenCompose`\u002F`thenCombine`),\nbuilt-in error handling, and easy fan-out\u002Ffan-in — far more flexible than the\nblocking `Future`.\n",{"id":287,"difficulty":63,"q":288,"a":289},"atomic-classes","What are the atomic classes and how do they work?","`java.util.concurrent.atomic` provides lock-free, thread-safe variables —\n`AtomicInteger`, `AtomicLong`, `AtomicReference`, etc. They use **CAS\n(compare-and-swap)** hardware instructions for atomic updates without locking.\n\n```java\nAtomicInteger count = new AtomicInteger();\ncount.incrementAndGet();          \u002F\u002F atomic ++\ncount.compareAndSet(5, 10);       \u002F\u002F set to 10 only if currently 5\nref.updateAndGet(v -> v + delta); \u002F\u002F atomic functional update\n```\n\nAtomics outperform `synchronized` for simple counters\u002Fflags under contention\n(no blocking), though heavy contention can cause CAS retry loops. For high\ncontention prefer `LongAdder`.\n",{"id":291,"difficulty":84,"q":292,"a":293},"cas","What is compare-and-swap (CAS)?","CAS is an atomic CPU instruction: \"if this memory location still holds the\n*expected* value, replace it with the *new* value, atomically; otherwise do\nnothing and report failure.\" It's the foundation of **lock-free** algorithms.\n\n```java\n\u002F\u002F typical lock-free retry loop\nint prev, next;\ndo {\n  prev = atomic.get();\n  next = prev + 1;\n} while (!atomic.compareAndSet(prev, next)); \u002F\u002F retry if another thread changed it\n```\n\nBecause no lock is held, there's no blocking or deadlock — but it can spin under\ncontention, and it has the **ABA problem** (a value changing A->B->A looks\nunchanged), which `AtomicStampedReference` solves with a version stamp.\n",{"id":295,"difficulty":84,"q":296,"a":297},"reentrantlock","What is ReentrantLock and how does it compare to synchronized?","`ReentrantLock` is an explicit lock with the same mutual-exclusion semantics as\n`synchronized` but **more features**: `tryLock()` (with timeout), interruptible\nlocking, **fairness** policy, and multiple **`Condition`** objects.\n\n```java\nReentrantLock lock = new ReentrantLock();\nlock.lock();\ntry { \u002F* critical section *\u002F }\nfinally { lock.unlock(); }   \u002F\u002F MUST unlock in finally\n\nif (lock.tryLock(1, TimeUnit.SECONDS)) { ... }  \u002F\u002F give up after 1s\n```\n\nTrade-off: `synchronized` is simpler and auto-releases on block exit;\n`ReentrantLock` is more powerful but you **must** `unlock()` in `finally` or you\nleak the lock. Use it only when you need its extra capabilities.\n",{"id":299,"difficulty":84,"q":300,"a":301},"read-write-lock","What is a ReadWriteLock?","A `ReadWriteLock` separates a **read lock** (shared — many readers at once) from\na **write lock** (exclusive). It boosts throughput for **read-heavy** data where\nwrites are rare, since concurrent reads don't block each other.\n\n```java\nReadWriteLock rw = new ReentrantReadWriteLock();\nrw.readLock().lock();   try { return cache.get(k); } finally { rw.readLock().unlock(); }\nrw.writeLock().lock();  try { cache.put(k, v); }     finally { rw.writeLock().unlock(); }\n```\n\nOnly one writer runs at a time and it excludes all readers. For very read-heavy\ncases, `StampedLock` (Java 8) adds optimistic reads that are even faster.\n",{"id":303,"difficulty":84,"q":304,"a":305},"threadlocal","What is ThreadLocal and when is it used?","`ThreadLocal\u003CT>` gives **each thread its own independent copy** of a variable,\nso there's no sharing and no synchronization needed. Common for per-thread\ncontext: `SimpleDateFormat` (not thread-safe), user\u002Frequest context, DB\nconnections.\n\n```java\nstatic final ThreadLocal\u003CSimpleDateFormat> FMT =\n    ThreadLocal.withInitial(() -> new SimpleDateFormat(\"yyyy-MM-dd\"));\nString today = FMT.get().format(new Date());  \u002F\u002F safe per-thread instance\n```\n\nCaution in **thread pools**: threads are reused, so you must **`remove()`** the\nvalue after use or it leaks into the next task (and can cause memory leaks).\n",{"id":307,"difficulty":84,"q":308,"a":309},"java-memory-model","What is the Java Memory Model and happens-before?","The Java Memory Model (JMM) defines **when writes by one thread become visible to\nanother** and what reorderings are allowed. The core concept is\n**happens-before**: if action A happens-before B, A's effects are guaranteed\nvisible to B.\n\nHappens-before edges include: program order within a thread; unlocking a monitor\n-> subsequent locking of it; a `volatile` write -> subsequent read; `Thread.start`\n-> the thread's actions; a thread's actions -> another's `join`.\n\n```java\nvolatile boolean ready;\nint data;\n\u002F\u002F Thread A:\ndata = 42; ready = true;          \u002F\u002F volatile write publishes `data`\n\u002F\u002F Thread B:\nif (ready) System.out.println(data); \u002F\u002F sees 42 — happens-before guarantees it\n```\n\nWithout a happens-before relationship, one thread may **never** see another's\nwrites (or see them reordered). This is *why* `volatile`\u002F`synchronized` matter.\n",{"id":311,"difficulty":63,"q":312,"a":313},"thread-safety","What does it mean for code to be thread-safe?","Thread-safe code behaves **correctly when accessed by multiple threads\nconcurrently**, without external synchronization, regardless of timing. You\nachieve it by: avoiding shared mutable state, **immutability**,\n**synchronization**, atomic variables, or thread-confinement (`ThreadLocal`).\n\n```java\n\u002F\u002F thread-safe by immutability — no state can change\nrecord Point(int x, int y) { }\n\u002F\u002F thread-safe by synchronization\nclass SafeCounter { private int n; synchronized void inc() { n++; } }\n```\n\nLevels range from **immutable** (always safe) -> **thread-safe** (handles its own\nsync) -> **conditionally safe** (some ops need external sync) -> **not\nthread-safe** (`ArrayList`, `HashMap`). The cheapest safety is having no shared\nmutable state at all.\n",{"id":315,"difficulty":84,"q":316,"a":317},"producer-consumer","How do you implement the producer-consumer pattern?","Producers add items to a shared buffer, consumers remove them; they must\ncoordinate so producers wait when full and consumers wait when empty. The\nidiomatic modern way is a **`BlockingQueue`**, which handles all the\nwaiting\u002Fnotifying internally.\n\n```java\nBlockingQueue\u003CTask> queue = new LinkedBlockingQueue\u003C>(100);\n\n\u002F\u002F producer\nqueue.put(task);        \u002F\u002F blocks if the queue is full\n\n\u002F\u002F consumer\nTask t = queue.take();  \u002F\u002F blocks if the queue is empty\n```\n\n`put`\u002F`take` block automatically — no manual `wait`\u002F`notify`. `ArrayBlockingQueue`\n(bounded) gives natural backpressure; `LinkedBlockingQueue` can be bounded or\nunbounded.\n",{"id":319,"difficulty":63,"q":320,"a":321},"countdownlatch","What are CountDownLatch and CyclicBarrier?","Both are synchronization aids that make threads wait for each other:\n\n- **`CountDownLatch`** — threads wait until a counter reaches zero; **one-shot**\n  (can't be reset). \"Wait for N tasks to finish.\"\n- **`CyclicBarrier`** — a fixed number of threads wait for **each other** at a\n  barrier point; **reusable** across rounds.\n\n```java\nCountDownLatch latch = new CountDownLatch(3);\nfor (int i = 0; i \u003C 3; i++)\n  pool.submit(() -> { work(); latch.countDown(); });\nlatch.await();   \u002F\u002F main thread blocks until all 3 finish\n```\n\n`CountDownLatch` is for \"main waits for workers\"; `CyclicBarrier` is for \"workers\nsync up repeatedly.\" `Semaphore` is a related tool that limits concurrent access\nto N permits.\n",{"id":323,"difficulty":63,"q":324,"a":325},"daemon-thread","What is a daemon thread?","A daemon thread is a **background thread that does not prevent the JVM from\nexiting**. The JVM shuts down once only daemon threads remain, abruptly stopping\nthem (their `finally` blocks may not run). Used for support tasks like GC,\nhousekeeping, and monitoring.\n\n```java\nThread t = new Thread(this::poll);\nt.setDaemon(true);   \u002F\u002F must be set BEFORE start()\nt.start();\n```\n\nUser (non-daemon) threads, by contrast, **keep the JVM alive** until they finish.\nSet the daemon flag before `start()` — changing it after throws\n`IllegalThreadStateException`. Don't use daemons for work that must complete.\n",{"id":327,"difficulty":84,"q":328,"a":329},"thread-interruption","How does thread interruption work?","Interruption is a **cooperative** signal, not a forced stop. `interrupt()` sets a\nthread's interrupt flag; the thread must **check it** (`isInterrupted()`) or be\nin a blocking call that throws `InterruptedException`. There is no safe way to\nforcibly kill a thread (`Thread.stop()` is deprecated and dangerous).\n\n```java\nwhile (!Thread.currentThread().isInterrupted()) {\n  try {\n    doWork();\n    Thread.sleep(100);\n  } catch (InterruptedException e) {\n    Thread.currentThread().interrupt(); \u002F\u002F restore the flag, then exit\n    break;\n  }\n}\n```\n\nBest practice: when you catch `InterruptedException` and can't propagate it,\n**restore the interrupt status** with `Thread.currentThread().interrupt()` so\ncallers still see it.\n",{"id":331,"difficulty":63,"q":332,"a":333},"synchronized-collections-conc","Why is ConcurrentHashMap preferred over synchronized maps?","`Collections.synchronizedMap` locks the **entire map** for every operation, so\nthreads serialize even on unrelated keys — a bottleneck. `ConcurrentHashMap`\nuses **fine-grained locking \u002F CAS on individual bins**, allowing many threads to\nread and write different buckets concurrently.\n\n```java\nMap\u003CString,Integer> m = new ConcurrentHashMap\u003C>();\nm.merge(word, 1, Integer::sum);     \u002F\u002F atomic compound update, no global lock\nm.computeIfAbsent(k, x -> load(x)); \u002F\u002F atomic\n```\n\nIt also offers **atomic** compound methods (`merge`, `computeIfAbsent`,\n`putIfAbsent`) and fail-safe iteration. The result is dramatically better\nthroughput under concurrency.\n",{"id":335,"difficulty":84,"q":336,"a":337},"false-sharing","What is false sharing?","False sharing is a performance problem (not a correctness bug) where two threads\nmodify **different variables that happen to sit on the same CPU cache line**.\nEach write **invalidates the whole line** in the other core's cache, forcing\nexpensive cache-coherence traffic even though the variables are independent.\n\n```java\n\u002F\u002F a[0] and a[1] may share a cache line; two threads hammering them contend\nlong[] counters = new long[2];\n\u002F\u002F padding or @Contended separates hot fields onto different lines\n```\n\nMitigations: pad hot fields apart, use `@jdk.internal.vm.annotation.Contended`,\nor use `LongAdder`, which internally stripes counters across cells to avoid\ncontention.\n",{"id":339,"difficulty":71,"q":340,"a":341},"thread-priority","How do thread priorities work?","Each thread has a priority from 1 (`MIN_PRIORITY`) to 10 (`MAX_PRIORITY`),\ndefault 5. It's only a **hint** to the OS scheduler about relative importance —\nnot a guarantee. Behavior is platform-dependent and often ignored.\n\n```java\nThread t = new Thread(task);\nt.setPriority(Thread.MAX_PRIORITY);  \u002F\u002F best-effort hint only\n```\n\nDon't build correctness on priorities — they can't ensure ordering and, on some\nplatforms, do almost nothing. For real coordination use explicit synchronization\nor executor configuration.\n",{"id":343,"difficulty":63,"q":344,"a":345},"synchronized-static","What is the difference between a synchronized instance method and a static one?","The difference is **which lock** is acquired:\n\n- A `synchronized` **instance** method locks on **`this`** (the object). Two\n  threads on *different instances* don't contend.\n- A `synchronized` **static** method locks on the **`Class`** object, shared by\n  all instances.\n\n```java\nclass C {\n  synchronized void a() { }          \u002F\u002F locks on this instance\n  static synchronized void b() { }   \u002F\u002F locks on C.class (one global lock)\n}\n```\n\nA subtle bug: `a()` and `b()` use **different locks**, so they can run\nsimultaneously even though both are \"synchronized.\" Mixing instance and static\nsynchronization on shared state doesn't protect it.\n",{"id":347,"difficulty":84,"q":348,"a":349},"double-checked-locking","What is double-checked locking and why does it need volatile?","Double-checked locking lazily initializes a singleton while only locking on the\nfirst call:\n\n```java\nclass Singleton {\n  private static volatile Singleton instance;   \u002F\u002F volatile is essential\n  static Singleton get() {\n    if (instance == null) {                      \u002F\u002F 1st check (no lock)\n      synchronized (Singleton.class) {\n        if (instance == null) {                  \u002F\u002F 2nd check (locked)\n          instance = new Singleton();\n        }\n      }\n    }\n    return instance;\n  }\n}\n```\n\nWithout **`volatile`**, another thread could see a **partially constructed**\nobject: `instance = new Singleton()` isn't atomic (allocate, construct, assign),\nand reordering could publish the reference before construction finishes.\n`volatile` forbids that reordering. (An enum or holder-class singleton avoids the\nwhole issue.)\n",{"id":351,"difficulty":84,"q":352,"a":353},"blocking-vs-nonblocking","What is the difference between blocking and non-blocking algorithms?","- **Blocking** algorithms use locks; a thread that can't proceed is **suspended**\n  (BLOCKED\u002FWAITING) until the lock frees. Simple, but a slow\u002Fdead lock-holder\n  stalls others (and risks deadlock).\n- **Non-blocking** (lock-free) algorithms use **CAS** retry loops; a thread never\n  suspends — it retries until it succeeds. No deadlock, better scalability, but\n  harder to write and can livelock\u002Fspin.\n\n```java\n\u002F\u002F non-blocking counter\nAtomicLong c = new AtomicLong();\nc.incrementAndGet();   \u002F\u002F CAS loop under the hood — never blocks\n```\n\n`java.util.concurrent` provides both: `ReentrantLock`\u002F`BlockingQueue` (blocking)\nand `Atomic*`\u002F`ConcurrentLinkedQueue` (non-blocking).\n",{"id":355,"difficulty":84,"q":356,"a":357},"virtual-threads","What are virtual threads (Project Loom)?","Virtual threads (Java 21) are **lightweight threads managed by the JVM**, not the\nOS. Millions can exist at once because a blocked virtual thread is **unmounted**\nfrom its carrier OS thread, freeing it for other work. This makes the simple\n\"thread-per-request\" blocking style scale like async code.\n\n```java\ntry (var executor = Executors.newVirtualThreadPerTaskExecutor()) {\n  for (var task : tasks) executor.submit(task); \u002F\u002F a virtual thread each\n}\n```\n\nThey're cheap to create and ideal for **I\u002FO-bound** workloads (many tasks\nblocking on network\u002FDB). For CPU-bound work, platform threads sized to the cores\nare still the right tool — virtual threads don't add CPU.\n",{"id":359,"difficulty":63,"q":360,"a":361},"synchronization-overhead","What is lock contention and how do you reduce it?","Lock contention occurs when many threads compete for the **same lock**, so they\nserialize and queue up — throughput collapses as cores sit idle waiting. The fix\nis to reduce how often and how long threads hold shared locks.\n\nStrategies:\n- **Shrink the critical section** — hold the lock for as little code as possible.\n- **Lock striping** — split one lock into many (what `ConcurrentHashMap` does).\n- **Use atomics \u002F lock-free** structures for simple state.\n- **Immutable or thread-local** data to avoid sharing.\n- **Read-write locks** when reads dominate.\n\n```java\n\u002F\u002F whole method locked     \u002F\u002F lock only the shared mutation\nsynchronized void m() {       void m() {\n  var x = expensive();          var x = expensive();\n  shared.add(x);                synchronized (shared) { shared.add(x); }\n}                             }\n```\n",{"id":363,"difficulty":63,"q":364,"a":365},"executor-shutdown","How do you properly shut down an ExecutorService?","Use the standard two-phase shutdown so in-flight tasks finish and threads are\nreleased (a pool's non-daemon threads otherwise keep the JVM alive):\n\n```java\npool.shutdown();                      \u002F\u002F stop accepting new tasks\ntry {\n  if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {\n    pool.shutdownNow();               \u002F\u002F interrupt running tasks\n    pool.awaitTermination(10, TimeUnit.SECONDS);\n  }\n} catch (InterruptedException e) {\n  pool.shutdownNow();\n  Thread.currentThread().interrupt();\n}\n```\n\n`shutdown()` is graceful (finish queued work); `shutdownNow()` interrupts active\ntasks and returns the unstarted ones. Forgetting to shut down a pool is a common\nresource\u002Fthread leak.\n",{"description":61},"Java concurrency interview questions — threads vs Runnable, synchronized, volatile, the memory model, deadlock, wait\u002Fnotify, executors, futures, CompletableFuture and atomic classes.","java\u002Fconcurrency\u002Fthreads","Threads & Synchronization","Concurrency","concurrency","bB9xo_QxZtFCRbhLK1eQaCAHZBmcvpo3dMNQY89_qMM",{"id":374,"title":375,"body":376,"description":61,"difficulty":63,"extension":64,"framework":49,"frameworkSlug":47,"meta":380,"navigation":66,"order":12,"path":381,"questions":382,"related":207,"seo":515,"seoDescription":516,"stem":517,"subtopic":375,"topic":518,"topicSlug":519,"updated":214,"__hash__":520},"qa\u002Fjava\u002Fexceptions\u002Fexception-handling.md","Exception Handling",{"type":58,"value":377,"toc":378},[],{"title":61,"searchDepth":22,"depth":22,"links":379},[],{},"\u002Fjava\u002Fexceptions\u002Fexception-handling",[383,387,391,395,399,403,407,411,415,419,423,427,431,435,439,443,447,451,455,459,463,467,471,475,479,483,487,491,495,499,503,507,511],{"id":384,"difficulty":71,"q":385,"a":386},"what-is-exception","What is an exception in Java?","An exception is an **object representing an abnormal event** that disrupts\nnormal flow — a division by zero, a missing file, a null dereference. When one\noccurs, the JVM creates an exception object and **propagates it up the call\nstack** until a matching `catch` handles it, or the thread terminates.\n\n```java\ntry {\n  int x = 10 \u002F 0;          \u002F\u002F throws ArithmeticException\n} catch (ArithmeticException e) {\n  System.out.println(\"Caught: \" + e.getMessage()); \u002F\u002F \"\u002F by zero\"\n}\n```\n\nExceptions separate error-handling code from the main logic and carry context\n(message + stack trace) to help diagnose what went wrong.\n",{"id":388,"difficulty":63,"q":389,"a":390},"exception-hierarchy","What does the Java exception hierarchy look like?","Everything throwable descends from **`Throwable`**, which splits into two\nbranches:\n\n- **`Error`** — serious problems the application shouldn't catch\n  (`OutOfMemoryError`, `StackOverflowError`). Unchecked.\n- **`Exception`** — conditions a program may want to handle.\n  - **`RuntimeException`** and its subclasses are **unchecked**.\n  - All other `Exception` subclasses are **checked**.\n\n```\nThrowable\n├── Error              (unchecked — don't catch)\n└── Exception\n    ├── RuntimeException   (unchecked)\n    └── IOException, SQLException... (checked)\n```\n\nSo \"checked vs unchecked\" is purely about whether the class sits under\n`RuntimeException`\u002F`Error` (unchecked) or elsewhere under `Exception` (checked).\n",{"id":392,"difficulty":63,"q":393,"a":394},"checked-vs-unchecked","What is the difference between checked and unchecked exceptions?","- **Checked** exceptions (subclasses of `Exception`, excluding\n  `RuntimeException`) are verified by the **compiler**: a method must either\n  `catch` them or declare `throws`. They represent recoverable, expected\n  conditions (`IOException`, `SQLException`).\n- **Unchecked** exceptions (`RuntimeException`\u002F`Error` subclasses) are **not**\n  compiler-enforced — usually programming bugs (`NullPointerException`,\n  `IllegalArgumentException`, `ArrayIndexOutOfBoundsException`).\n\n```java\nvoid read() throws IOException {     \u002F\u002F checked -> must declare or catch\n  Files.readString(Path.of(\"x\"));\n}\nvoid bug() {\n  String s = null;\n  s.length();                        \u002F\u002F unchecked -> no declaration required\n}\n```\n\nGuideline: checked for conditions callers can reasonably recover from;\nunchecked for bugs and contract violations.\n",{"id":396,"difficulty":63,"q":397,"a":398},"error-vs-exception","What is the difference between Error and Exception?","Both extend `Throwable`, but:\n\n- **`Error`** signals a serious, usually **unrecoverable** JVM\u002Fsystem problem —\n  `OutOfMemoryError`, `StackOverflowError`, `NoClassDefFoundError`. Applications\n  **should not catch** these; there's typically nothing useful to do.\n- **`Exception`** signals an **application-level** condition that code may\n  reasonably handle.\n\n```java\ntry {\n  recurse();                  \u002F\u002F infinite recursion\n} catch (StackOverflowError e) {\n  \u002F\u002F technically possible, but a code smell — don't rely on this\n}\n```\n\nBoth are unchecked (well, `Error` is), but the intent differs: `Error` = \"the\nplatform is broken\"; `Exception` = \"your program hit a handleable situation.\"\n",{"id":400,"difficulty":71,"q":401,"a":402},"try-catch-finally","What are try, catch and finally blocks?","- **`try`** — wraps code that might throw.\n- **`catch`** — handles a specific exception type (you can have several).\n- **`finally`** — runs **always**, whether or not an exception occurred (and\n  even after a `return`) — for cleanup like closing resources.\n\n```java\ntry {\n  risky();\n} catch (IOException e) {\n  log(e);\n} finally {\n  cleanup();   \u002F\u002F runs no matter what\n}\n```\n\nA `try` needs at least one `catch` **or** a `finally`. `catch` blocks are checked\ntop-down, so order **subclasses before superclasses**.\n",{"id":404,"difficulty":84,"q":405,"a":406},"finally-always-runs","Does finally always run? Are there exceptions?","`finally` runs after the `try`\u002F`catch` in virtually all cases — including when\nthe `try` or `catch` executes a `return`, `break`, or `continue`. The **only**\nways to skip it: `System.exit()`, the JVM crashing, an infinite loop\u002Fdeadlock in\nthe `try`, or the thread being killed.\n\n```java\nint f() {\n  try {\n    return 1;     \u002F\u002F evaluated...\n  } finally {\n    System.out.println(\"still runs\"); \u002F\u002F ...but finally runs before returning\n  }\n}\n```\n\nBeware: a `return` (or `throw`) **inside `finally`** overrides the try's return\nand **swallows pending exceptions** — a notorious bug, so never return\u002Fthrow\nfrom `finally`.\n",{"id":408,"difficulty":63,"q":409,"a":410},"try-with-resources","What is try-with-resources?","A `try` with resources declared in parentheses **auto-closes** them when the\nblock exits — normally or via exception — as long as they implement\n`AutoCloseable`. It replaces verbose `finally { x.close(); }` blocks and avoids\nleaks.\n\n```java\ntry (var br = Files.newBufferedReader(path);\n     var conn = dataSource.getConnection()) {\n  return br.readLine();\n}   \u002F\u002F br and conn closed automatically, in reverse order\n```\n\nResources close in **reverse order** of declaration. It also handles the case\nwhere both the body *and* `close()` throw — see suppressed exceptions.\n",{"id":412,"difficulty":63,"q":413,"a":414},"autocloseable","What is AutoCloseable and how do you use it?","`AutoCloseable` is the interface (one method, `close()`) that makes a class\neligible for **try-with-resources**. Implement it for any resource that needs\ndeterministic cleanup — connections, streams, locks.\n\n```java\nclass Connection implements AutoCloseable {\n  Connection() { System.out.println(\"open\"); }\n  public void close() { System.out.println(\"closed\"); }\n}\ntry (Connection c = new Connection()) {\n  \u002F\u002F use c\n} \u002F\u002F close() called automatically\n```\n\n`Closeable` (from `java.io`) extends `AutoCloseable` but narrows `close()` to\nthrow `IOException`. Prefer `AutoCloseable` for general resources.\n",{"id":416,"difficulty":63,"q":417,"a":418},"multi-catch","What is multi-catch and when is it useful?","Multi-catch (Java 7+) handles **several exception types in one `catch`** using\nthe `|` separator, when the handling logic is identical — reducing duplication.\n\n```java\ntry {\n  parseAndStore();\n} catch (IOException | SQLException e) {   \u002F\u002F one handler for both\n  log.error(\"operation failed\", e);\n  throw new ServiceException(e);\n}\n```\n\nRules: the types must **not be subclasses of one another** (redundant), and the\ncaught variable `e` is **implicitly final**. Use it to collapse copy-pasted\ncatch blocks.\n",{"id":420,"difficulty":71,"q":421,"a":422},"throw-vs-throws","What is the difference between throw and throws?","- **`throw`** is a **statement** that actually raises an exception object, now.\n- **`throws`** is a **method declaration** clause announcing which checked\n  exceptions the method may propagate to its caller.\n\n```java\nvoid withdraw(int amt) throws InsufficientFundsException { \u002F\u002F declares\n  if (amt > balance) {\n    throw new InsufficientFundsException(); \u002F\u002F raises\n  }\n}\n```\n\nMnemonic: `throw` *does* it (one object), `throws` *warns about* it (a list of\ntypes). You can `throw` unchecked exceptions without declaring them.\n",{"id":424,"difficulty":63,"q":425,"a":426},"custom-exception","How do you create a custom exception?","Extend `Exception` (for checked) or `RuntimeException` (for unchecked), and\nprovide constructors that pass the message and cause to `super`.\n\n```java\npublic class InsufficientFundsException extends RuntimeException {\n  private final int shortfall;\n  public InsufficientFundsException(int shortfall) {\n    super(\"Short by \" + shortfall + \" cents\");\n    this.shortfall = shortfall;\n  }\n  public int getShortfall() { return shortfall; }\n}\n```\n\nCustom exceptions let you carry **domain-specific data** and let callers\n`catch` precisely. Prefer **unchecked** for programming\u002Fbusiness errors unless\nthe caller can genuinely recover (then checked).\n",{"id":428,"difficulty":63,"q":429,"a":430},"exception-chaining","What is exception chaining (the cause)?","Exception chaining wraps a low-level exception inside a higher-level one while\n**preserving the original as the \"cause\"**, so the full diagnostic trail\nsurvives. Pass the cause to the constructor or `initCause`.\n\n```java\ntry {\n  jdbc.query();\n} catch (SQLException e) {\n  throw new DataAccessException(\"load failed\", e); \u002F\u002F e becomes the cause\n}\n```\n\nThe printed stack trace shows `Caused by: java.sql.SQLException...`. Chaining\nlets you translate exceptions across abstraction layers without losing the root\ncause — far better than catching and re-throwing a bare new exception.\n",{"id":432,"difficulty":84,"q":433,"a":434},"swallowing","What does it mean to \"swallow\" an exception and why is it bad?","Swallowing is catching an exception and **doing nothing** (or only an empty\nblock), hiding the failure so the program continues in a possibly broken state\nand you lose all diagnostic information.\n\n```java\n\u002F\u002F swallowed — silent failure, impossible to debug\ntry { risky(); } catch (Exception e) { }\n\n\u002F\u002F at minimum, log it (and preserve the stack trace)\ntry { risky(); } catch (Exception e) {\n  log.error(\"risky() failed\", e);\n  throw e;                 \u002F\u002F or wrap\u002Frethrow if you can't handle it\n}\n```\n\nRule: never have an empty catch. Either **handle** it meaningfully, **log** it,\nor **rethrow**. Empty catches are one of the most damaging anti-patterns in\nproduction code.\n",{"id":436,"difficulty":63,"q":437,"a":438},"catch-order","Why does catch block order matter?","`catch` blocks are evaluated **top to bottom**, and the first matching type\nwins. So a **more specific** exception must come **before** its superclass —\notherwise the broad catch shadows the specific one and the compiler reports\n\"exception has already been caught.\"\n\n```java\ntry {\n  read();\n} catch (FileNotFoundException e) {  \u002F\u002F specific first\n  \u002F\u002F handle missing file\n} catch (IOException e) {            \u002F\u002F broader after\n  \u002F\u002F handle other I\u002FO errors\n}\n```\n\nReversing them (`IOException` first) is a **compile error**, because\n`FileNotFoundException` could never be reached.\n",{"id":440,"difficulty":71,"q":441,"a":442},"npe-causes","What causes a NullPointerException and how do you prevent it?","An NPE happens when you **dereference `null`** — call a method, access a field,\nindex an array, or unbox a null wrapper.\n\n```java\nString s = map.get(\"missing\"); \u002F\u002F null\ns.length();                    \u002F\u002F NullPointerException\n```\n\nPrevention: validate inputs (`Objects.requireNonNull`), use `Optional` for\nmaybe-absent values, prefer constants on the left of `equals`\n(`\"x\".equals(s)`), use `getOrDefault`, and embrace **Java 14+ helpful NPE\nmessages** which name the exact expression that was null\n(`Cannot invoke \"String.length()\" because \"s\" is null`).\n",{"id":444,"difficulty":63,"q":445,"a":446},"optional","How does Optional help with null handling?","`Optional\u003CT>` is a container that **explicitly represents \"value or absent,\"**\nforcing callers to deal with the empty case instead of risking an NPE on a\nsurprise null.\n\n```java\nOptional\u003CUser> user = repo.findById(id);\nString name = user.map(User::name)\n                  .orElse(\"unknown\");        \u002F\u002F default if absent\nuser.ifPresent(u -> sendEmail(u));           \u002F\u002F act only if present\n```\n\nBest practices: use it as a **return type** for \"might not find one\"; **don't**\nuse it for fields, parameters, or collections (return an empty collection\ninstead); and avoid `.get()` without checking (`isPresent`\u002F`orElseThrow`).\n",{"id":448,"difficulty":71,"q":449,"a":450},"stack-trace","What is a stack trace and how do you read it?","A stack trace is the **snapshot of the call stack** at the moment an exception\nwas created — it lists, top to bottom, the method calls from where the\nexception was thrown back up to the entry point.\n\n```\njava.lang.NullPointerException: ... \"user\" is null\n    at com.app.Service.process(Service.java:42)   \u003C- where it was thrown\n    at com.app.Controller.handle(Controller.java:18)\n    at com.app.Main.main(Main.java:9)\nCaused by: java.sql.SQLException: ...             \u003C- original cause\n```\n\nRead the **top frame** for where it blew up, and follow **`Caused by:`** down to\nthe root cause. Print it with `e.printStackTrace()` or, better, `log.error(msg,\ne)`.\n",{"id":452,"difficulty":84,"q":453,"a":454},"finally-return-trap","What happens when both try and finally have a return?","A `return` in `finally` **overrides** any return or exception from the `try`\u002F\n`catch` — the try's pending result (or thrown exception) is **discarded\nsilently**. This is a subtle, dangerous bug.\n\n```java\nint f() {\n  try {\n    return 1;\n  } finally {\n    return 2;   \u002F\u002F method returns 2; the \"return 1\" is lost\n  }\n}\nint g() {\n  try {\n    throw new RuntimeException();\n  } finally {\n    return 0;   \u002F\u002F swallows the exception entirely\n  }\n}\n```\n\nNever put `return`\u002F`throw`\u002F`break` in `finally`. Use `finally` strictly for\ncleanup, not control flow.\n",{"id":456,"difficulty":84,"q":457,"a":458},"suppressed-exceptions","What are suppressed exceptions?","In try-with-resources, if the **body throws** *and* `close()` also throws, Java\nkeeps the body's exception as primary and attaches the close exception as a\n**suppressed** exception (so neither is lost). You retrieve them via\n`getSuppressed()`.\n\n```java\ntry (AutoCloseable r = () -> { throw new IOException(\"close failed\"); }) {\n  throw new RuntimeException(\"body failed\"); \u002F\u002F primary\n}\n\u002F\u002F RuntimeException propagates; the IOException is in getSuppressed()\n```\n\nBefore try-with-resources, a `close()` exception in a manual `finally` would\n*replace* the original — hiding the real cause. Suppression fixes that. The\nprintout shows `Suppressed:` beneath the main trace.\n",{"id":460,"difficulty":63,"q":461,"a":462},"rethrow","What are the ways to rethrow an exception?","- **Rethrow as-is** — let it propagate after partial handling (log, then\n  `throw e`).\n- **Wrap and rethrow** — translate to a higher-level type, preserving the cause\n  (`throw new ServiceException(e)`).\n- **Rethrow a different type** — only when it improves the abstraction.\n\n```java\ntry {\n  repo.save(order);\n} catch (SQLException e) {\n  metrics.increment(\"save.failure\");\n  throw new PersistenceException(\"could not save order\", e); \u002F\u002F wrap + chain\n}\n```\n\nAlways pass the original as the **cause** when wrapping, so debugging info\nsurvives. Don't catch just to rethrow the *same* type with no added value.\n",{"id":464,"difficulty":63,"q":465,"a":466},"best-practices","What are best practices for exception handling?","- **Catch specific** exceptions, not bare `Exception`\u002F`Throwable`.\n- **Never swallow** — handle, log, or rethrow.\n- **Throw early, catch late** — validate inputs at the boundary; handle where\n  you have context to recover.\n- **Don't use exceptions for control flow** (they're expensive and obscure\n  intent).\n- **Preserve the cause** when wrapping.\n- **Clean up with try-with-resources**, not manual `finally`.\n- Include **useful messages** with context.\n\n```java\n\u002F\u002F specific, contextual, chained\ncatch (IOException e) {\n  throw new ConfigException(\"failed to load \" + path, e);\n}\n```\n",{"id":468,"difficulty":84,"q":469,"a":470},"exception-performance","Why are exceptions expensive, and what is the cost?","The main cost is **capturing the stack trace** when the exception is\nconstructed — the JVM walks the entire call stack and records each frame. The\n`throw`\u002F`catch` mechanism itself is cheap; building the trace is not. So using\nexceptions for ordinary control flow (e.g. loop termination) is slow.\n\n```java\n\u002F\u002F for hot paths where the trace isn't needed, you can disable it:\nclass FastException extends RuntimeException {\n  FastException() { super(null, null, false, false); } \u002F\u002F no stack trace\n}\n```\n\nGuidance: reserve exceptions for **exceptional** conditions; use return values,\n`Optional`, or sentinels for expected outcomes. Don't catch-and-ignore in tight\nloops.\n",{"id":472,"difficulty":63,"q":473,"a":474},"custom-checked-or-unchecked","Should a custom exception be checked or unchecked?","Decide by whether the **caller can reasonably recover**:\n\n- **Checked** (`extends Exception`) — recoverable, expected conditions the\n  caller should be forced to handle (e.g. `FileNotFoundException`-like cases).\n- **Unchecked** (`extends RuntimeException`) — programming errors, contract\n  violations, or failures the caller usually can't fix (validation,\n  configuration, most business-rule violations).\n\n```java\n\u002F\u002F recoverable -> checked\nclass RetryableNetworkException extends Exception { }\n\u002F\u002F bug \u002F unrecoverable -> unchecked\nclass InvalidConfigException extends RuntimeException { }\n```\n\nModern frameworks (Spring, etc.) lean heavily toward **unchecked** to avoid\n`throws` clutter, translating low-level checked exceptions into runtime ones.\n",{"id":476,"difficulty":84,"q":477,"a":478},"catch-throwable","Why should you avoid catching Throwable or Exception broadly?","Catching `Throwable` also catches **`Error`s** (`OutOfMemoryError`,\n`StackOverflowError`) that you can't sensibly recover from and may make things\nworse. Catching `Exception` broadly hides bugs (an unexpected\n`NullPointerException` gets swallowed by a handler meant for I\u002FO errors).\n\n```java\n\u002F\u002F too broad — masks programming bugs and serious errors\ntry { work(); } catch (Throwable t) { \u002F* keep going *\u002F }\n\n\u002F\u002F catch what you can actually handle\ntry { work(); } catch (IOException e) { recover(e); }\n```\n\nCatch the **narrowest** type that you genuinely know how to handle; let\neverything else propagate to a top-level handler.\n",{"id":480,"difficulty":63,"q":481,"a":482},"exception-translation","What is exception translation across layers?","Exception translation means **converting low-level exceptions into ones\nappropriate to the current abstraction layer**, so callers aren't coupled to\nimplementation details (a service shouldn't leak `SQLException`).\n\n```java\n\u002F\u002F persistence layer hides JDBC details from the service layer\ntry {\n  return jdbcTemplate.query(sql);\n} catch (SQLException e) {\n  throw new RepositoryException(\"query failed\", e); \u002F\u002F translate + chain\n}\n```\n\nAlways keep the original as the cause. This is exactly what Spring's\n`DataAccessException` hierarchy does — translating vendor-specific SQL errors\ninto a consistent, unchecked API.\n",{"id":484,"difficulty":63,"q":485,"a":486},"assert","What is the assert keyword and how does it relate to exceptions?","`assert` checks an invariant that should *always* be true; if false it throws an\n`AssertionError`. Assertions are **disabled by default** at runtime (enable with\nthe `-ea` JVM flag), so they're for **catching developer bugs during\ndevelopment\u002Ftesting**, not validating production input.\n\n```java\nassert index >= 0 : \"index must be non-negative, got \" + index;\n```\n\nBecause they can be turned off, **never** use `assert` for argument validation\nor anything with side effects — use `if (...) throw new\nIllegalArgumentException(...)` for real input checks.\n",{"id":488,"difficulty":63,"q":489,"a":490},"nested-try","How do nested try blocks and exception propagation work?","A `try` can contain another `try`. If an inner block doesn't catch an\nexception, it **propagates outward** to the nearest enclosing handler — and\nkeeps unwinding the stack until something catches it or the thread dies.\n\n```java\ntry {\n  try {\n    throw new IllegalStateException(\"inner\");\n  } finally {\n    System.out.println(\"inner finally\"); \u002F\u002F runs during unwind\n  }\n} catch (IllegalStateException e) {\n  System.out.println(\"caught in outer\"); \u002F\u002F handled here\n}\n```\n\nDuring propagation, every `finally` along the way still executes. This unwinding\nis how an exception thrown deep in the call stack reaches a top-level handler.\n",{"id":492,"difficulty":84,"q":493,"a":494},"uncaught-handler","What happens to an uncaught exception in a thread?","If an exception propagates out of a thread's `run`\u002F`main` without being caught,\nthe thread **terminates**, and the JVM hands the exception to that thread's\n**`UncaughtExceptionHandler`** (by default printing the stack trace to\n`System.err`). Other threads keep running; the **whole JVM only exits if it was\nthe last non-daemon thread**.\n\n```java\nThread.setDefaultUncaughtExceptionHandler((t, e) ->\n    log.error(\"Uncaught in \" + t.getName(), e));\n```\n\nSetting a handler is essential for background threads, whose failures would\notherwise vanish silently.\n",{"id":496,"difficulty":63,"q":497,"a":498},"illegalargument-vs-illegalstate","When do you use IllegalArgumentException vs IllegalStateException?","Both are standard unchecked exceptions for **precondition violations**:\n\n- **`IllegalArgumentException`** — a **method argument** is invalid (wrong\n  value\u002Frange).\n- **`IllegalStateException`** — the **object is in the wrong state** for the\n  operation, regardless of the arguments.\n\n```java\nvoid setAge(int age) {\n  if (age \u003C 0) throw new IllegalArgumentException(\"age \u003C 0: \" + age);\n}\nvoid start() {\n  if (running) throw new IllegalStateException(\"already started\");\n}\n```\n\nUse the built-in exceptions (plus `NullPointerException` for null args,\nidiomatically via `Objects.requireNonNull`) rather than inventing custom ones\nfor these common cases.\n",{"id":500,"difficulty":63,"q":501,"a":502},"finally-resource-leak","Why is manual finally cleanup error-prone compared to try-with-resources?","Manual cleanup in `finally` is verbose and easy to get wrong: you must\nnull-check, nest try\u002Fcatch around `close()`, and handle the case where `close()`\nitself throws (which would hide the original exception). Multiple resources\nmultiply the boilerplate.\n\n```java\n\u002F\u002F error-prone manual style\nBufferedReader br = null;\ntry {\n  br = Files.newBufferedReader(path);\n} finally {\n  if (br != null) br.close(); \u002F\u002F close() can throw and mask the real error\n}\n\n\u002F\u002F correct, concise, handles suppression\ntry (var br = Files.newBufferedReader(path)) { }\n```\n\nTry-with-resources closes in the right order, handles nulls, and records\nsuppressed exceptions — strictly better.\n",{"id":504,"difficulty":84,"q":505,"a":506},"rethrow-precise","What is more precise rethrow analysis (Java 7+)?","Since Java 7, the compiler analyzes which checked exceptions can **actually**\nflow out of a `try`, so you can catch a broad type but **rethrow with a\nnarrower `throws`** clause — as long as the caught variable is effectively\nfinal.\n\n```java\nvoid m() throws IOException, SQLException {  \u002F\u002F precise, not \"throws Exception\"\n  try {\n    if (cond) throw new IOException();\n    else throw new SQLException();\n  } catch (Exception e) {   \u002F\u002F catch broadly...\n    log(e);\n    throw e;                \u002F\u002F ...rethrow: compiler knows it's IOException|SQLException\n  }\n}\n```\n\nBefore Java 7 you'd have been forced to declare `throws Exception`. This lets you\nlog centrally while keeping precise method signatures.\n",{"id":508,"difficulty":84,"q":509,"a":510},"exception-in-static-init","What happens if an exception is thrown in a static initializer?","If a `static` initializer (or static field initialization) throws, the JVM wraps\nit in an **`ExceptionInInitializerError`** and the class **fails to initialize**.\nWorse, the class is marked unusable: any later attempt to use it throws\n**`NoClassDefFoundError`**.\n\n```java\nclass Config {\n  static final int VALUE = compute(); \u002F\u002F if compute() throws...\n  static int compute() { throw new RuntimeException(\"boom\"); }\n}\n\u002F\u002F First use -> ExceptionInInitializerError\n\u002F\u002F Subsequent uses -> NoClassDefFoundError\n```\n\nThis is a confusing failure mode in real systems — a misconfigured static\nconstant can make a class permanently unloadable. Keep static initialization\nsimple and defensive.\n",{"id":512,"difficulty":63,"q":513,"a":514},"logging-vs-throwing","Should you log and throw, or just one?","Doing **both** at every level causes \"log spam\" — the same exception printed\nrepeatedly as it propagates. The common rule: **either handle it (and log) OR\npropagate it (and let a higher layer log)** — not both at every level.\n\n```java\n\u002F\u002F log-and-throw at every layer -> duplicated stack traces\ncatch (IOException e) { log.error(\"failed\", e); throw e; }\n\n\u002F\u002F propagate now, log once at the top-level boundary\ncatch (IOException e) { throw new ServiceException(e); }\n\u002F\u002F ... and a single handler at the controller\u002Fedge logs it\n```\n\nLog **once**, at the boundary where the exception is finally handled (e.g. a\ncontroller advice or a top-level `catch`), with full context.\n",{"description":61},"Java exception handling interview questions — checked vs unchecked, the exception hierarchy, try\u002Fcatch\u002Ffinally, try-with-resources, custom exceptions, chaining, and common pitfalls like swallowing exceptions.","java\u002Fexceptions\u002Fexception-handling","Exceptions","exceptions","wArz93b9NB6yDuB0xDMten2Mp8DtYbRC8psG-wPq3ak",{"id":522,"title":523,"body":524,"description":61,"difficulty":71,"extension":64,"framework":49,"frameworkSlug":47,"meta":528,"navigation":66,"order":12,"path":529,"questions":530,"related":207,"seo":663,"seoDescription":664,"stem":665,"subtopic":666,"topic":667,"topicSlug":668,"updated":214,"__hash__":669},"qa\u002Fjava\u002Ffundamentals\u002Fdata-types-variables.md","Data Types Variables",{"type":58,"value":525,"toc":526},[],{"title":61,"searchDepth":22,"depth":22,"links":527},[],{},"\u002Fjava\u002Ffundamentals\u002Fdata-types-variables",[531,535,539,543,547,551,555,559,563,567,571,575,579,583,587,591,595,599,603,607,611,615,619,623,627,631,635,639,643,647,651,655,659],{"id":532,"difficulty":71,"q":533,"a":534},"primitives-list","What are the eight primitive types in Java?","Java has exactly **eight** primitives, each with a fixed size and no methods:\n\n| Type | Size | Range \u002F notes |\n| ---- | ---- | ------------- |\n| `byte` | 8-bit | −128…127 |\n| `short` | 16-bit | −32,768…32,767 |\n| `int` | 32-bit | ~±2.1 billion (default for integer literals) |\n| `long` | 64-bit | very large; literal suffix `L` |\n| `float` | 32-bit | IEEE-754, suffix `f` |\n| `double` | 64-bit | IEEE-754 (default for decimal literals) |\n| `char` | 16-bit | a single UTF-16 code unit, `0`…`65535` |\n| `boolean` | JVM-defined | `true` \u002F `false` |\n\nPrimitives hold their value **directly** (on the stack or inline in an\nobject), unlike objects which are accessed through references. Everything else\nin Java — `String`, arrays, your classes — is a reference type.\n",{"id":536,"difficulty":71,"q":537,"a":538},"primitive-vs-wrapper","What is the difference between a primitive and its wrapper class?","Every primitive has an **object wrapper** in `java.lang`: `int`->`Integer`,\n`double`->`Double`, `char`->`Character`, `boolean`->`Boolean`, etc. The primitive\nstores a raw value; the wrapper is a full **object** on the heap that *contains*\nthe value plus object overhead (header, identity, can be `null`).\n\n```java\nint a = 5;              \u002F\u002F raw value, can never be null\nInteger b = 5;          \u002F\u002F object reference, can be null\nInteger c = null;       \u002F\u002F legal; int x = c; would throw NullPointerException\n```\n\nYou need wrappers wherever Java requires an object: generics\n(`List\u003CInteger>`, never `List\u003Cint>`), collections, and nullable fields.\nPrimitives are faster and lighter, so prefer them for arithmetic and hot loops.\n",{"id":540,"difficulty":63,"q":541,"a":542},"autoboxing","What are autoboxing and unboxing?","**Autoboxing** is the compiler automatically converting a primitive to its\nwrapper; **unboxing** is the reverse. It lets primitives and wrappers mix\nseamlessly — `Integer.valueOf(...)` \u002F `intValue()` calls are inserted for you.\n\n```java\nList\u003CInteger> nums = new ArrayList\u003C>();\nnums.add(5);            \u002F\u002F autobox: int 5 -> Integer.valueOf(5)\nint first = nums.get(0); \u002F\u002F unbox: Integer -> intValue()\n```\n\nThe hidden cost: unboxing a `null` wrapper throws **`NullPointerException`**,\nand boxing in a tight loop creates throwaway objects (GC pressure). A classic\ntrap is `Integer sum = 0; for (...) sum += x;` which boxes\u002Funboxes every\niteration — use a primitive `int` accumulator instead.\n",{"id":544,"difficulty":84,"q":545,"a":546},"integer-cache","Why does == sometimes return true and sometimes false for equal Integer values?","Because `==` on wrappers compares **references**, and Java **caches** boxed\n`Integer` objects for the range **−128 to 127** (the `IntegerCache`). Values in\nthat range return the *same* cached object; values outside it create new\nobjects each time.\n\n```java\nInteger a = 127, b = 127;\nSystem.out.println(a == b);   \u002F\u002F true  — same cached object\n\nInteger c = 128, d = 128;\nSystem.out.println(c == d);   \u002F\u002F false — two distinct objects\nSystem.out.println(c.equals(d)); \u002F\u002F true — value comparison\n```\n\nThe lesson interviewers want: **always compare wrapper values with\n`.equals()`** (or unbox to primitives), never `==`. The cache exists because\nsmall integers are extremely common, so reusing them saves allocations.\n",{"id":548,"difficulty":71,"q":549,"a":550},"equals-vs-eqeq","What is the difference between == and .equals() in Java?","`==` compares **references** for objects (do both variables point to the *same*\nobject?) and raw **values** for primitives. `.equals()` is a method that\ncompares **logical equality** — what \"equal\" means is defined by the class.\n\n```java\nString a = new String(\"hi\");\nString b = new String(\"hi\");\na == b        \u002F\u002F false — two different objects\na.equals(b)   \u002F\u002F true  — same characters\n\nint x = 5, y = 5;\nx == y        \u002F\u002F true  — primitive value comparison\n```\n\n`Object.equals` defaults to `==` (reference identity), so a class must\n**override** `equals` to get meaningful value comparison — `String`,\n`Integer`, and the collections all do.\n",{"id":552,"difficulty":63,"q":553,"a":554},"string-immutable","Why are Strings immutable in Java?","A `String`'s internal character data is `final` and never changes after\nconstruction; any \"modification\" returns a **new** `String`. Immutability buys\nseveral things: **safe sharing** in the string pool, **thread safety** without\nlocks, usability as **hash keys** (the hash can be cached and never goes\nstale), and **security** (a path\u002FURL can't be mutated after a check).\n\n```java\nString s = \"hello\";\ns.concat(\" world\");      \u002F\u002F creates a new String, discarded here\nSystem.out.println(s);   \u002F\u002F \"hello\" — s itself is unchanged\ns = s.concat(\" world\");  \u002F\u002F reassign the reference to the new String\n```\n\nThe trade-off is that heavy string building creates garbage — which is exactly\nwhy `StringBuilder` exists.\n",{"id":556,"difficulty":63,"q":557,"a":558},"string-pool","What is the String pool (string interning)?","The string pool is a special area where the JVM stores **one shared copy** of\neach distinct string **literal**. Two identical literals refer to the same\npooled object, saving memory. Strings made with `new` are *not* pooled — they\ncreate a fresh heap object — unless you call `.intern()`.\n\n```java\nString a = \"hi\";          \u002F\u002F pooled\nString b = \"hi\";          \u002F\u002F same pooled object\nString c = new String(\"hi\"); \u002F\u002F new heap object, NOT pooled\na == b           \u002F\u002F true\na == c           \u002F\u002F false\na == c.intern()  \u002F\u002F true — intern() returns the pooled copy\n```\n\nThis is why beginners hit bugs comparing strings with `==`: literals seem to\nwork (same pooled object) but `new`\u002Fcomputed strings don't. Always use\n`.equals()`.\n",{"id":560,"difficulty":63,"q":561,"a":562},"stringbuilder","What is the difference between String, StringBuilder and StringBuffer?","- **`String`** — immutable; every concatenation allocates a new object. Fine\n  for a few fixed pieces, wasteful in loops.\n- **`StringBuilder`** — a **mutable**, resizable character buffer. Not\n  synchronized, so it's fast; the right default for building strings.\n- **`StringBuffer`** — same API as `StringBuilder` but **synchronized**\n  (thread-safe), hence slower. Rarely needed today.\n\n```java\n\u002F\u002F O(n²) garbage — a new String each iteration\nString r = \"\";\nfor (String p : parts) r += p;\n\n\u002F\u002F one buffer, amortized O(n)\nStringBuilder sb = new StringBuilder();\nfor (String p : parts) sb.append(p);\nString r2 = sb.toString();\n```\n\nNote the compiler optimizes simple `a + b + c` into `StringBuilder` calls — the\nproblem is concatenation **inside loops**, where it can't.\n",{"id":564,"difficulty":84,"q":565,"a":566},"pass-by-value","Is Java pass-by-value or pass-by-reference?","Java is **always pass-by-value** — no exceptions. The subtlety is that for\nobjects, the *value being copied is the reference* (the pointer), not the\nobject. So a method can **mutate** the object the reference points to, but\n**reassigning** the parameter doesn't affect the caller's variable.\n\n```java\nvoid mutate(int[] arr) { arr[0] = 99; }   \u002F\u002F changes the caller's array\nvoid reassign(int[] arr) { arr = new int[]{0}; } \u002F\u002F no effect on caller\n\nint[] a = {1};\nmutate(a);    \u002F\u002F a is now {99}\nreassign(a);  \u002F\u002F a is still {99} — the copied reference was replaced locally\n```\n\nSay it crisply in an interview: \"Java passes references **by value**.\" The\nreference is copied; both copies point at the same object until one is\nreassigned.\n",{"id":568,"difficulty":71,"q":569,"a":570},"default-values","What are the default values of fields in Java?","**Instance and static fields** are automatically initialized to a zero value:\n`0` for numeric primitives, `false` for `boolean`, `\\u0000` (the null character) for `char`, and\n**`null`** for any reference type.\n\n```java\nclass Box {\n  int n;        \u002F\u002F 0\n  boolean ok;   \u002F\u002F false\n  String name;  \u002F\u002F null\n}\n```\n\nThe crucial exception: **local variables get no default**. The compiler\n*requires* you to assign one before use, or it's a compile error (\"variable\nmight not have been initialized\") — a deliberate guard against reading garbage.\n",{"id":572,"difficulty":63,"q":573,"a":574},"int-overflow","What happens on integer overflow in Java?","Integer arithmetic **wraps around silently** using two's-complement — no\nexception is thrown. Exceeding `Integer.MAX_VALUE` rolls over to\n`Integer.MIN_VALUE`.\n\n```java\nint max = Integer.MAX_VALUE;   \u002F\u002F 2_147_483_647\nSystem.out.println(max + 1);   \u002F\u002F -2147483648  (wraps, no error)\n\n\u002F\u002F common bug: this overflows before being assigned to long\nlong bad = 1_000_000 * 1_000_000;        \u002F\u002F -727379968\nlong good = 1_000_000L * 1_000_000;      \u002F\u002F 1000000000000 (promote first)\n```\n\nMitigations: promote to `long`, use `Math.addExact`\u002F`multiplyExact` (which\n*throw* `ArithmeticException` on overflow), or `BigInteger` for unbounded math.\n",{"id":576,"difficulty":63,"q":577,"a":578},"float-precision","Why is 0.1 + 0.2 not exactly 0.3 in Java?","`float` and `double` are **binary IEEE-754** floating point. Many decimal\nfractions (like `0.1`) have no exact binary representation, so they're stored\nas the nearest approximation and tiny errors accumulate.\n\n```java\nSystem.out.println(0.1 + 0.2);   \u002F\u002F 0.30000000000000004\nSystem.out.println(0.1 + 0.2 == 0.3); \u002F\u002F false\n```\n\nFor money or anything needing exact decimals, use **`BigDecimal`** (and\nconstruct it from a *String*, not a double):\n\n```java\nnew BigDecimal(\"0.1\").add(new BigDecimal(\"0.2\")); \u002F\u002F 0.3 exactly\n```\n\nNever compare floats with `==`; compare within a small epsilon instead.\n",{"id":580,"difficulty":71,"q":581,"a":582},"char-type","What is the char type and how does it relate to int?","`char` is a **16-bit unsigned** integer holding a single UTF-16 code unit\n(`'A'`, `'7'`, `'€'`). Because it's numeric under the hood, it participates in\narithmetic and auto-promotes to `int`.\n\n```java\nchar c = 'A';\nint code = c;            \u002F\u002F 65 (implicit widening)\nchar next = (char) (c + 1); \u002F\u002F 'B' (must cast back, since c+1 is int)\nSystem.out.println('a' + 'b'); \u002F\u002F 195, not \"ab\" — numeric addition!\n```\n\nA frequent gotcha: `'a' + 'b'` adds the code points, while `\"\" + 'a' + 'b'`\nconcatenates. Characters beyond the Basic Multilingual Plane (emoji) need two\nchars (a surrogate pair) or `int` code points.\n",{"id":584,"difficulty":63,"q":585,"a":586},"casting","What is the difference between widening and narrowing conversions?","**Widening** (smaller -> larger type, e.g. `int`->`long`->`double`) is safe and\n**implicit** — no data loss, no cast needed. **Narrowing** (larger -> smaller,\ne.g. `double`->`int`) can lose data, so it requires an **explicit cast** and you\naccept the truncation.\n\n```java\nint i = 100;\nlong l = i;          \u002F\u002F widening — automatic\ndouble d = i;        \u002F\u002F widening — automatic\n\ndouble pi = 3.99;\nint n = (int) pi;    \u002F\u002F narrowing — explicit; truncates to 3 (not rounded)\nbyte b = (byte) 300; \u002F\u002F narrowing — overflows to 44\n```\n\nNarrowing **truncates toward zero** for floating->integer (it doesn't round),\nand wraps for integer overflow — both common interview \"what prints?\" traps.\n",{"id":588,"difficulty":63,"q":589,"a":590},"var-keyword","What is the var keyword and what are its limits?","`var` (Java 10+) is **local variable type inference**: the compiler infers the\nstatic type from the initializer. It's still **statically typed** — `var` is\nnot a dynamic\u002F`Object` type — just less verbose.\n\n```java\nvar list = new ArrayList\u003CString>();  \u002F\u002F inferred ArrayList\u003CString>\nvar count = 10;                      \u002F\u002F int\nfor (var entry : map.entrySet()) { } \u002F\u002F inferred Map.Entry\u003C...>\n```\n\nRestrictions: only for **local variables with an initializer**. You **can't**\nuse `var` for fields, method parameters, return types, or without an\ninitializer (`var x;` is illegal), and `var x = null;` won't compile (no type\nto infer).\n",{"id":592,"difficulty":63,"q":593,"a":594},"final-keyword","What does the final keyword mean for variables?","A `final` variable can be **assigned only once**. For a primitive that fixes\nthe value; for a reference it fixes **which object** the variable points to —\nthe object itself can still be mutated.\n\n```java\nfinal int MAX = 10;     \u002F\u002F MAX = 11; would not compile\nfinal List\u003CString> xs = new ArrayList\u003C>();\nxs.add(\"ok\");           \u002F\u002F mutating the object is allowed\nxs = new ArrayList\u003C>(); \u002F\u002F reassigning the reference is not\n```\n\n`final` also applies to fields (must be set by the end of construction),\nmethod parameters, and is required for variables a lambda\u002Fanonymous class\ncaptures (they must be `final` or *effectively final*).\n",{"id":596,"difficulty":63,"q":597,"a":598},"static-vs-instance","What is the difference between static and instance variables?","A **static** (class) variable belongs to the **class** — there's exactly **one\ncopy** shared by all instances. An **instance** variable belongs to each\n**object** — every `new` gets its own copy.\n\n```java\nclass Counter {\n  static int total;   \u002F\u002F one shared across all Counters\n  int id;             \u002F\u002F one per instance\n  Counter() { id = ++total; }\n}\nnew Counter(); \u002F\u002F id=1, total=1\nnew Counter(); \u002F\u002F id=2, total=2  (total is shared)\n```\n\nAccess statics via the class name (`Counter.total`). Statics are initialized\nwhen the class is loaded and live for the program's lifetime, which is why\nmutable static state is a common source of bugs and memory leaks.\n",{"id":600,"difficulty":71,"q":601,"a":602},"literals","How do numeric literals and underscores work in Java?","Literals default to `int` (integers) and `double` (decimals); suffixes change\nthat: `L`\u002F`l` for `long`, `f`\u002F`F` for `float`, `d`\u002F`D` for `double`. You can\nalso write binary (`0b`), octal (`0`), and hex (`0x`) literals, and use\n**underscores** as digit separators for readability.\n\n```java\nlong big   = 10_000_000_000L;  \u002F\u002F L needed — exceeds int range\nfloat rate = 1.5f;\nint  mask  = 0xFF;             \u002F\u002F 255 in hex\nint  bits  = 0b1010;           \u002F\u002F 10 in binary\nint  million = 1_000_000;      \u002F\u002F underscores ignored by the compiler\n```\n\nForgetting the `L` on a large literal is a classic bug: `10_000_000_000` alone\nwon't compile because it overflows `int`.\n",{"id":604,"difficulty":71,"q":605,"a":606},"ternary","What is the ternary operator and a common pitfall with it?","The ternary `condition ? a : b` is an **expression** that evaluates to `a` when\nthe condition is true, else `b` — a compact `if\u002Felse` that returns a value.\n\n```java\nString label = (n % 2 == 0) ? \"even\" : \"odd\";\nint max = (a > b) ? a : b;\n```\n\nThe subtle trap is **type promotion \u002F unboxing** of the two branches: if one\nbranch is a primitive and the other a wrapper, the result is unboxed, so a\n`null` wrapper branch can throw `NullPointerException`:\n\n```java\nInteger x = null;\nObject o = true ? 0 : x;   \u002F\u002F fine\nint bad  = false ? 0 : x;  \u002F\u002F NPE — both branches unboxed to int\n```\n",{"id":608,"difficulty":71,"q":609,"a":610},"arrays-basics","How are arrays represented in Java?","An array is an **object** on the heap with a fixed length set at creation; the\nvariable holds a reference to it. Elements are stored contiguously and default\nto their zero value (`0`\u002F`false`\u002F`null`).\n\n```java\nint[] a = new int[3];        \u002F\u002F {0, 0, 0}\nint[] b = {1, 2, 3};         \u002F\u002F array initializer\nString[] names = new String[2]; \u002F\u002F {null, null}\nSystem.out.println(a.length);   \u002F\u002F 3 — a field, not a method\n```\n\nKey facts: `length` is a **field** (no parentheses), the size is **immutable**\nonce created (need a bigger array? allocate a new one or use `ArrayList`), and\nout-of-bounds access throws `ArrayIndexOutOfBoundsException`.\n",{"id":612,"difficulty":63,"q":613,"a":614},"multidim-arrays","How do multidimensional and jagged arrays work?","Java has no true 2D arrays — a `int[][]` is an **array of arrays**. That means\nrows can have different lengths (a **jagged** array), and each row is a separate\nheap object.\n\n```java\nint[][] grid = new int[2][3];   \u002F\u002F 2 rows, 3 cols each\ngrid[0][1] = 5;\n\nint[][] jagged = new int[2][];  \u002F\u002F rows allocated separately\njagged[0] = new int[]{1, 2};\njagged[1] = new int[]{3, 4, 5}; \u002F\u002F different length — legal\n```\n\nBecause rows are independent objects, iterating with `row.length` (not a fixed\ncolumn count) is the safe pattern.\n",{"id":616,"difficulty":63,"q":617,"a":618},"type-promotion","How does numeric promotion work in arithmetic expressions?","In arithmetic, operands smaller than `int` (`byte`, `short`, `char`) are first\n**promoted to `int`**, and if any operand is `long`\u002F`float`\u002F`double` the whole\nexpression is promoted to the widest type. This is why byte arithmetic returns\nan `int`.\n\n```java\nbyte a = 10, b = 20;\nbyte c = a + b;        \u002F\u002F won't compile — a + b is int\nbyte d = (byte)(a + b); \u002F\u002F cast back\n\nint i = 5;\ndouble e = i \u002F 2;      \u002F\u002F 2.0 — int division happens FIRST, then widens\ndouble f = i \u002F 2.0;    \u002F\u002F 2.5 — one double operand promotes the division\n```\n\nThe `5 \u002F 2 == 2` integer-division surprise is the most common version of this\nin interviews.\n",{"id":620,"difficulty":71,"q":621,"a":622},"null-keyword","What is null and what can and cannot be null in Java?","`null` is a special literal meaning a reference points to **no object**. Only\n**reference types** can be `null` — primitives cannot. Using a `null` reference\n(calling a method, accessing a field, unboxing) throws **`NullPointerException`**.\n\n```java\nString s = null;\ns.length();          \u002F\u002F NullPointerException\nint[] a = null;\nint n = a.length;    \u002F\u002F NPE\nInteger boxed = null;\nint x = boxed;       \u002F\u002F NPE — unboxing null\n```\n\n`null` is the same regardless of type, and `instanceof` on `null` is always\n`false`. Modern Java offers `Optional` and (Java 14+) **helpful NPE messages**\nthat name the exact variable that was null.\n",{"id":624,"difficulty":63,"q":625,"a":626},"object-class","What methods does every object inherit from Object?","Every class implicitly extends `java.lang.Object`, inheriting:\n\n- `equals(Object)` — logical equality (default: reference identity).\n- `hashCode()` — int hash, must be consistent with `equals`.\n- `toString()` — string form (default: `ClassName@hexHash`).\n- `getClass()` — runtime class object.\n- `clone()` — shallow copy (protected; needs `Cloneable`).\n- `wait()\u002Fnotify()\u002FnotifyAll()` — thread coordination on the object's monitor.\n- `finalize()` — deprecated cleanup hook.\n\n```java\nclass Point {\n  int x, y;\n  @Override public String toString() { return \"(\" + x + \",\" + y + \")\"; }\n}\n```\n\nYou'll most often override `equals`, `hashCode`, and `toString` — and the\nfirst two must be overridden **together** to honor their contract.\n",{"id":628,"difficulty":71,"q":629,"a":630},"scope-block","What is variable scope in Java?","A variable is visible only within the **block (`{ }`) it's declared in**, and\nceases to exist when that block ends. Inner blocks can see outer variables, but\nnot vice versa, and you can't redeclare a name that's already in scope.\n\n```java\nvoid m() {\n  int x = 1;\n  if (x > 0) {\n    int y = 2;        \u002F\u002F visible only inside this if\n    System.out.println(x + y);\n  }\n  \u002F\u002F y is out of scope here\n}\n```\n\nLoop variables (`for (int i ...)`) are scoped to the loop. Unlike fields, local\nvariables have **no default** and must be assigned before use.\n",{"id":632,"difficulty":63,"q":633,"a":634},"implicit-explicit-cast","When do you need an explicit cast for reference types?","Assigning a subclass reference to a superclass variable (**upcasting**) is\nimplicit and always safe. Going the other way (**downcasting**) needs an\nexplicit cast *and* is checked at runtime — a wrong cast throws\n`ClassCastException`.\n\n```java\nObject o = \"hello\";          \u002F\u002F upcast — implicit\nString s = (String) o;       \u002F\u002F downcast — explicit, succeeds\nInteger bad = (Integer) o;   \u002F\u002F compiles, but throws ClassCastException\n\nif (o instanceof String str) \u002F\u002F pattern matching (Java 16+) guards the cast\n    System.out.println(str.length());\n```\n\nGuard downcasts with `instanceof` (ideally the pattern form) to avoid runtime\nfailures.\n",{"id":636,"difficulty":71,"q":637,"a":638},"constants","How do you define a constant in Java?","The idiom is **`static final`** with an UPPER_SNAKE_CASE name. `static` means\none shared copy; `final` means it can't be reassigned. The compiler can inline\n`static final` primitive\u002F`String` constants for efficiency.\n\n```java\npublic class Config {\n  public static final int MAX_RETRIES = 3;\n  public static final String APP_NAME = \"Interviews\";\n}\n```\n\nNote `final` on a reference constant only freezes the reference, not the\nobject — `static final List\u003CString> X = new ArrayList\u003C>()` can still be mutated,\nso use `List.of(...)` or `Collections.unmodifiableList` for a truly constant\ncollection.\n",{"id":640,"difficulty":71,"q":641,"a":642},"wrapper-parsing","How do you convert between Strings and numbers?","Use the wrapper classes' static methods. `parseXxx` returns a **primitive**;\n`valueOf` returns a **wrapper object**. Going the other way, `String.valueOf`\nor concatenation produces text.\n\n```java\nint n      = Integer.parseInt(\"42\");     \u002F\u002F primitive int\nInteger w  = Integer.valueOf(\"42\");       \u002F\u002F Integer object\ndouble d   = Double.parseDouble(\"3.14\");\nString s   = String.valueOf(42);          \u002F\u002F \"42\"\nString s2  = \"\" + 42;                      \u002F\u002F \"42\" (concatenation)\n```\n\nA malformed string throws **`NumberFormatException`**, so wrap parsing of\nuntrusted input in a try\u002Fcatch or validate first.\n",{"id":644,"difficulty":63,"q":645,"a":646},"bitwise","What are the bitwise and shift operators in Java?","Java has `&` (AND), `|` (OR), `^` (XOR), `~` (NOT), and shifts `\u003C\u003C`, `>>`\n(signed\u002Farithmetic right shift), and `>>>` (unsigned\u002Flogical right shift, which\nfills with zeros).\n\n```java\n5 & 3    \u002F\u002F 1   (0101 & 0011)\n5 | 3    \u002F\u002F 7\n5 ^ 3    \u002F\u002F 6\n1 \u003C\u003C 4   \u002F\u002F 16  (multiply by 2^4)\n-8 >> 1  \u002F\u002F -4  (sign-preserving)\n-8 >>> 28 \u002F\u002F 15 (zero-filled — treats bits as unsigned)\n```\n\n`>>>` is unique to Java (no unsigned types) and is the trap: it's the only shift\nthat ignores the sign bit. Bitwise `&`\u002F`|` also work on `boolean` as\nnon-short-circuiting logical operators.\n",{"id":648,"difficulty":71,"q":649,"a":650},"enhanced-for","What is the enhanced for loop and its limitations?","The enhanced for (for-each) iterates any array or `Iterable` without an index,\nreading each element in turn.\n\n```java\nfor (String name : names) {\n  System.out.println(name);\n}\n```\n\nIts limits, often asked about: you **can't get the index**, you can't iterate\ntwo collections in lockstep, and you **can't modify the collection** during\niteration (it uses an iterator under the hood, so adding\u002Fremoving throws\n`ConcurrentModificationException`). Reassigning the loop variable also doesn't\nchange the underlying element — use a classic indexed `for` or an explicit\n`Iterator` for those cases.\n",{"id":652,"difficulty":71,"q":653,"a":654},"ternary-vs-if","What is the difference between an expression and a statement?","An **expression** evaluates to a value (`a + b`, `x > 0`, `obj.method()`); a\n**statement** is a complete instruction that performs an action (`if`, `for`,\nassignments, `return`). Expressions can be nested inside statements.\n\n```java\nint max = (a > b) ? a : b;   \u002F\u002F ternary is an EXPRESSION (has a value)\nif (a > b) { max = a; }      \u002F\u002F if is a STATEMENT (no value)\n```\n\nThis distinction explains why you can write `int x = a > b ? a : b;` but not\n`int x = if (...) ...;` — `if` produces no value. (Java's `switch` gained an\n*expression* form in Java 14 that does yield a value.)\n",{"id":656,"difficulty":71,"q":657,"a":658},"text-blocks","What are text blocks in Java?","Text blocks (Java 15+) are multi-line string literals delimited by triple\nquotes `\"\"\"`. They preserve line breaks and let you write JSON, SQL, or HTML\nwithout escaping quotes or concatenating lines.\n\n```java\nString json = \"\"\"\n    {\n      \"name\": \"Ada\",\n      \"role\": \"engineer\"\n    }\n    \"\"\";\n```\n\nIncidental leading whitespace is stripped based on the closing delimiter's\nindentation, and the result is just a normal `String` — so it still goes\nthrough the pool and supports all `String` methods.\n",{"id":660,"difficulty":71,"q":661,"a":662},"identifier-rules","What are the rules for valid Java identifiers?","An identifier may contain letters, digits, `_`, and `$`, but **can't start with\na digit**, can't be a **reserved keyword** (`class`, `int`, `for`…), and is\n**case-sensitive** (`count` ≠ `Count`). Unicode letters are allowed.\n\n```java\nint count, _total, $price, αβγ;  \u002F\u002F all legal\nint 2fast;   \u002F\u002F can't start with a digit\nint class;   \u002F\u002F reserved keyword\n```\n\nBy convention (not enforced): `camelCase` for variables\u002Fmethods,\n`PascalCase` for types, `UPPER_SNAKE_CASE` for constants, and `$` is left for\ngenerated code.\n",{"description":61},"Java data types and variables interview questions — primitives vs wrappers, autoboxing, Integer caching, String immutability and the pool, pass-by-value, casting and the var keyword.","java\u002Ffundamentals\u002Fdata-types-variables","Data Types & Variables","Fundamentals","fundamentals","_N5UicxRw1mn1pojTIjQziRqx6EuAJ7Vz7sfDiCpglY",{"id":671,"title":672,"body":673,"description":61,"difficulty":63,"extension":64,"framework":49,"frameworkSlug":47,"meta":677,"navigation":66,"order":22,"path":678,"questions":679,"related":207,"seo":816,"seoDescription":817,"stem":818,"subtopic":819,"topic":667,"topicSlug":668,"updated":214,"__hash__":820},"qa\u002Fjava\u002Ffundamentals\u002Foop.md","Oop",{"type":58,"value":674,"toc":675},[],{"title":61,"searchDepth":22,"depth":22,"links":676},[],{},"\u002Fjava\u002Ffundamentals\u002Foop",[680,684,688,692,696,700,704,708,712,716,720,724,728,732,736,740,744,748,752,756,760,764,768,772,776,780,784,788,792,796,800,804,808,812],{"id":681,"difficulty":71,"q":682,"a":683},"four-pillars","What are the four pillars of object-oriented programming?","- **Encapsulation** — bundle data with the methods that operate on it and hide\n  internal state behind a public API (private fields + getters\u002Fsetters).\n- **Abstraction** — expose *what* an object does, hide *how*, via interfaces\n  and abstract classes.\n- **Inheritance** — a subclass reuses and extends a superclass's members\n  (`extends`).\n- **Polymorphism** — one reference type, many runtime forms; the actual\n  object's overridden method is called.\n\n```java\nclass Animal { String sound() { return \"...\"; } }\nclass Dog extends Animal { String sound() { return \"Woof\"; } } \u002F\u002F inheritance + override\nAnimal a = new Dog();   \u002F\u002F polymorphism\na.sound();              \u002F\u002F \"Woof\"\n```\n\nA good one-liner: encapsulation hides data, abstraction hides complexity,\ninheritance reuses behavior, polymorphism varies it.\n",{"id":685,"difficulty":71,"q":686,"a":687},"encapsulation","What is encapsulation and why does it matter?","Encapsulation means keeping fields **private** and exposing controlled access\nthrough methods, so an object protects its own invariants and you can change the\ninternals without breaking callers.\n\n```java\nclass Account {\n  private double balance;           \u002F\u002F hidden state\n  public void deposit(double amt) {\n    if (amt \u003C= 0) throw new IllegalArgumentException();\n    balance += amt;                 \u002F\u002F validated mutation\n  }\n  public double getBalance() { return balance; }\n}\n```\n\nBenefits: validation in one place, freedom to refactor representation, easier\ndebugging (state changes go through known methods), and thread-safety hooks. A\npublic mutable field gives up all of these.\n",{"id":689,"difficulty":71,"q":690,"a":691},"abstraction","What is abstraction and how is it achieved in Java?","Abstraction is exposing a **simplified contract** while hiding implementation\ndetail. In Java you achieve it with **interfaces** (pure contract) and\n**abstract classes** (partial implementation). Callers depend on the abstract\ntype, not the concrete class.\n\n```java\ninterface PaymentGateway { void charge(int cents); }\n\nclass StripeGateway implements PaymentGateway {\n  public void charge(int cents) { \u002F* API calls hidden here *\u002F }\n}\n\nPaymentGateway gw = new StripeGateway(); \u002F\u002F code depends only on the contract\n```\n\nThe payoff is decoupling: you can swap `StripeGateway` for `PayPalGateway`\nwithout touching the calling code — the basis of \"program to an interface.\"\n",{"id":693,"difficulty":71,"q":694,"a":695},"inheritance","What is inheritance and what does Java not allow?","Inheritance lets a subclass acquire the fields and methods of a superclass with\n`extends`, modeling an **is-a** relationship and enabling reuse + polymorphism.\n\n```java\nclass Vehicle { void start() { } }\nclass Car extends Vehicle { void honk() { } } \u002F\u002F Car is-a Vehicle\n```\n\nJava allows **single inheritance** of classes only — a class can extend exactly\none superclass (to avoid the \"diamond problem\"). It *can* implement **multiple\ninterfaces**, which is how Java gets multiple-type flexibility without\nmultiple class inheritance. `final` classes can't be extended at all.\n",{"id":697,"difficulty":63,"q":698,"a":699},"polymorphism","What is polymorphism and what are its forms?","Polymorphism = \"many forms.\" Java has two kinds:\n\n- **Runtime (dynamic) polymorphism** — method **overriding**. The JVM picks the\n  method based on the *actual object* at runtime (dynamic dispatch).\n- **Compile-time (static) polymorphism** — method **overloading**. The compiler\n  picks the method based on the *declared argument types*.\n\n```java\nAnimal a = new Dog();\na.sound();   \u002F\u002F runtime: Dog's override is chosen\n\nprint(5);    \u002F\u002F compile-time: print(int)\nprint(\"hi\"); \u002F\u002F compile-time: print(String)\n```\n\n\"Polymorphism\" in interviews usually means the runtime kind — the engine behind\n`List\u003CShape>` calling each shape's own `area()`.\n",{"id":701,"difficulty":63,"q":702,"a":703},"overloading-vs-overriding","What is the difference between overloading and overriding?","| | Overloading | Overriding |\n| --- | --- | --- |\n| What | Same name, **different parameters** | Subclass **replaces** a superclass method |\n| Signature | Must differ (type\u002Fcount) | Must be **identical** |\n| Bound | **Compile time** (static) | **Run time** (dynamic) |\n| Return type | Can differ | Same or covariant |\n\n```java\nclass Calc {\n  int add(int a, int b) { return a + b; }          \u002F\u002F overload 1\n  double add(double a, double b) { return a + b; }  \u002F\u002F overload 2\n}\nclass Base { void greet() { } }\nclass Sub extends Base { @Override void greet() { } } \u002F\u002F override\n```\n\nOverloading is about offering variations of an operation; overriding is about\nspecializing inherited behavior. Use `@Override` so the compiler verifies you\nactually overrode (and didn't accidentally overload).\n",{"id":705,"difficulty":63,"q":706,"a":707},"abstract-vs-interface","What is the difference between an abstract class and an interface?","- **Abstract class** — can have state (fields), constructors, and a mix of\n  concrete and abstract methods. A class extends **one**. Models an\n  *is-a* with shared implementation.\n- **Interface** — a contract; historically only abstract methods, now also\n  `default`\u002F`static`\u002F`private` methods, but **no instance state** (only\n  `public static final` constants). A class implements **many**.\n\n```java\nabstract class Shape {\n  private String name;            \u002F\u002F state allowed\n  abstract double area();         \u002F\u002F subclasses must implement\n  String describe() { return name + \": \" + area(); }\n}\ninterface Drawable { void draw(); default void hide() { } }\n```\n\nRule of thumb: use an **interface** for a capability multiple unrelated classes\ncan have (`Comparable`, `Runnable`); use an **abstract class** when subclasses\nshare state or implementation and form a tight family.\n",{"id":709,"difficulty":84,"q":710,"a":711},"inheritance-vs-composition","When should you favor composition over inheritance?","**Inheritance** (is-a) tightly couples a subclass to its parent's\nimplementation; changes to the base can silently break subclasses (the \"fragile\nbase class\" problem). **Composition** (has-a) builds behavior by *holding*\nother objects and delegating — looser coupling, more flexible.\n\n```java\n\u002F\u002F inheritance misused: a Stack is-a List? leaks all List methods\nclass Stack\u003CT> extends ArrayList\u003CT> { }\n\n\u002F\u002F composition: Stack HAS a list, exposes only stack operations\nclass Stack\u003CT> {\n  private final List\u003CT> items = new ArrayList\u003C>();\n  void push(T t) { items.add(t); }\n  T pop() { return items.remove(items.size() - 1); }\n}\n```\n\nGuideline (\"favor composition over inheritance\"): use inheritance only for a\ntrue is-a with a stable base designed for extension; otherwise compose. It also\nsidesteps single-inheritance limits.\n",{"id":713,"difficulty":63,"q":714,"a":715},"super-keyword","What does the super keyword do?","`super` refers to the **immediate superclass**. It does two jobs: call the\nparent **constructor** (`super(args)`, must be the first statement) and call an\n**overridden** parent method or access a parent field (`super.method()`).\n\n```java\nclass Animal {\n  Animal(String name) { }\n  void describe() { System.out.println(\"an animal\"); }\n}\nclass Dog extends Animal {\n  Dog(String name) {\n    super(name);              \u002F\u002F chain to parent constructor\n  }\n  @Override void describe() {\n    super.describe();         \u002F\u002F reuse parent behavior\n    System.out.println(\"...specifically a dog\");\n  }\n}\n```\n\nIf you don't call `super(...)` explicitly, the compiler inserts a no-arg\n`super()` — which fails to compile if the parent has no no-arg constructor.\n",{"id":717,"difficulty":71,"q":718,"a":719},"this-keyword","What does the this keyword refer to in Java?","`this` is a reference to the **current object**. Uses: disambiguate a field\nfrom a same-named parameter, call another constructor in the same class\n(`this(...)`, constructor chaining), and pass the current instance to other\nmethods.\n\n```java\nclass Point {\n  int x, y;\n  Point(int x, int y) {\n    this.x = x;          \u002F\u002F field vs parameter\n    this.y = y;\n  }\n  Point() { this(0, 0); } \u002F\u002F chain to the other constructor\n}\n```\n\n`this(...)` for constructor chaining, like `super(...)`, must be the first\nstatement — so you can't use both in one constructor.\n",{"id":721,"difficulty":71,"q":722,"a":723},"constructor","What is a constructor and what are its rules?","A constructor initializes a new object. It has the **class's name**, **no\nreturn type**, and runs when you use `new`. If you write none, the compiler\nsupplies a **default no-arg** constructor.\n\n```java\nclass User {\n  String name;\n  User() { this(\"anon\"); }      \u002F\u002F no-arg, chains\n  User(String name) { this.name = name; } \u002F\u002F parameterized\n}\n```\n\nRules interviewers probe: defining *any* constructor removes the free default\none; constructors can be overloaded; they're **not inherited** (but a subclass\nmust call one via `super`); and `private` constructors enable singletons and\nfactory-only construction.\n",{"id":725,"difficulty":63,"q":726,"a":727},"constructor-chaining","What is the order of execution when an object is constructed?","Construction runs **top-down** through the hierarchy:\n\n1. Static fields\u002Fblocks run **once** when the class first loads.\n2. On `new`: the superclass constructor runs first (via `super`), all the way\n   up to `Object`.\n3. Then instance field initializers and instance initializer blocks run.\n4. Then the rest of the subclass constructor body.\n\n```java\nclass A { A() { System.out.println(\"A ctor\"); } }\nclass B extends A {\n  int x = init();\n  int init() { System.out.println(\"B field\"); return 1; }\n  B() { System.out.println(\"B ctor\"); }\n}\n\u002F\u002F new B() prints: A ctor -> B field -> B ctor\n```\n\nA famous trap: calling an **overridable method from a constructor** runs the\nsubclass override *before* the subclass's fields are initialized — so it may see\n`null`\u002F`0`.\n",{"id":729,"difficulty":71,"q":730,"a":731},"access-modifiers","What are the four access modifiers in Java?","From most to least restrictive:\n\n- `private` — same class only.\n- *(default \u002F package-private)* — same package only (no keyword).\n- `protected` — same package **plus** subclasses (even in other packages).\n- `public` — everywhere.\n\n```java\npublic class Api {\n  private int secret;       \u002F\u002F class only\n  int packageScoped;        \u002F\u002F package\n  protected int forSubs;    \u002F\u002F package + subclasses\n  public int open;          \u002F\u002F everyone\n}\n```\n\nDefault the most restrictive that works (usually `private` fields) — it\nminimizes coupling. Note `protected` also grants package access, which surprises\npeople who think it's \"subclasses only.\"\n",{"id":733,"difficulty":63,"q":734,"a":735},"static-keyword","What does static mean for methods, fields and nested classes?","`static` binds a member to the **class** rather than an instance:\n\n- **static field** — one shared copy across all instances.\n- **static method** — called on the class, has **no `this`**, can't access\n  instance members directly (utility methods, factories).\n- **static nested class** — doesn't hold a reference to an outer instance.\n- **static block** — runs once at class load for static setup.\n\n```java\nclass MathUtil {\n  static final double PI = 3.14159;\n  static int square(int n) { return n * n; } \u002F\u002F MathUtil.square(5)\n}\n```\n\nBecause static methods aren't tied to an object, they **can't be overridden**\n(only *hidden*) and don't participate in runtime polymorphism.\n",{"id":737,"difficulty":63,"q":738,"a":739},"final-class-method","What does final mean for classes and methods?","- **`final` class** — cannot be extended (e.g. `String`, `Integer`). Locks the\n  design and lets the JIT optimize.\n- **`final` method** — cannot be overridden by subclasses; preserves critical\n  behavior.\n- **`final` field** — assign-once (constant once set).\n\n```java\nfinal class Constants { }          \u002F\u002F no subclassing\nclass Base {\n  final void critical() { }        \u002F\u002F subclasses can't override\n}\n```\n\nCommon reasons: immutability (a class meant to be immutable is often `final`),\nsecurity\u002Finvariant protection, and clarity of intent. It's the opposite of\n\"open for extension,\" so use it deliberately.\n",{"id":741,"difficulty":84,"q":742,"a":743},"equals-hashcode","What is the equals\u002FhashCode contract?","If you override `equals`, you **must** override `hashCode`, obeying:\n\n1. Equal objects (`a.equals(b)`) **must** have equal hash codes.\n2. `equals` must be reflexive, symmetric, transitive, and consistent.\n3. Unequal objects *may* share a hash code (collisions are allowed).\n\n```java\nclass Point {\n  final int x, y;\n  @Override public boolean equals(Object o) {\n    if (this == o) return true;\n    if (!(o instanceof Point p)) return false;\n    return x == p.x && y == p.y;\n  }\n  @Override public int hashCode() { return Objects.hash(x, y); }\n}\n```\n\nBreak the contract and **hash-based collections silently misbehave**: a\n`HashMap`\u002F`HashSet` may fail to find an object whose `hashCode` doesn't match\nits `equals`. Use `Objects.hash(...)` \u002F `Objects.equals(...)` to implement them.\n",{"id":745,"difficulty":71,"q":746,"a":747},"tostring","Why and how do you override toString?","The default `toString` returns `ClassName@hexHashCode` — useless in logs. Override\nit to return a readable representation, which is automatically used in string\nconcatenation, `println`, and debuggers.\n\n```java\nclass User {\n  String name; int age;\n  @Override public String toString() {\n    return \"User{name=\" + name + \", age=\" + age + \"}\";\n  }\n}\nSystem.out.println(new User()); \u002F\u002F User{name=null, age=0}\n```\n\nIt's purely for human-readable diagnostics — don't parse it programmatically.\nIDEs and `record`s can generate it for you.\n",{"id":749,"difficulty":63,"q":750,"a":751},"interface-default","What are default methods in interfaces and why were they added?","A **default method** provides a body inside an interface using the `default`\nkeyword. They were added in Java 8 so interfaces could **evolve** — e.g. adding\n`forEach` to `Iterable` — **without breaking** every existing implementer.\n\n```java\ninterface Greeter {\n  String name();\n  default String greet() { return \"Hello, \" + name(); } \u002F\u002F optional to override\n}\n```\n\nIf a class inherits conflicting defaults from two interfaces, it **must\noverride** to resolve the ambiguity (it can call `Iface.super.method()`).\nInterfaces can also have `static` and `private` helper methods now — but still\nno instance state.\n",{"id":753,"difficulty":63,"q":754,"a":755},"marker-interface","What is a marker interface?","A marker interface has **no methods** — it just *tags* a class so that code (or\nthe JVM) can detect a capability at runtime via `instanceof`. Classic examples:\n`Serializable`, `Cloneable`, `RandomAccess`.\n\n```java\nclass Config implements Serializable { } \u002F\u002F \"this class may be serialized\"\n```\n\nThe JVM checks `if (obj instanceof Serializable)` before serializing. Modern\nJava often prefers **annotations** for metadata, but marker interfaces still\ngive you compile-time type checking and `instanceof` support that annotations\ndon't.\n",{"id":757,"difficulty":63,"q":758,"a":759},"enum-basics","What are enums and what can they do beyond constants?","An `enum` defines a fixed set of named instances. Unlike `int` constants,\nenums are **type-safe**, can have **fields, constructors, and methods**, and\neach constant can even override behavior.\n\n```java\nenum Planet {\n  EARTH(9.81), MARS(3.71);\n  private final double gravity;\n  Planet(double g) { this.gravity = g; }   \u002F\u002F constructor\n  double weight(double mass) { return mass * gravity; }\n}\nPlanet.MARS.weight(70);  \u002F\u002F type-safe, behavior attached\n```\n\nEnums are implicitly `final` singletons (one instance per constant), work in\n`switch`, provide `values()`\u002F`valueOf()`\u002F`ordinal()`, and are the recommended\nway to implement singletons.\n",{"id":761,"difficulty":63,"q":762,"a":763},"record-class","What are records in Java?","A `record` (Java 16+) is a concise, **immutable** data carrier. From a one-line\ndeclaration the compiler generates a canonical constructor, `private final`\nfields, accessors, and `equals`\u002F`hashCode`\u002F`toString`.\n\n```java\nrecord Point(int x, int y) { }\n\nPoint p = new Point(1, 2);\np.x();                       \u002F\u002F accessor (no \"get\" prefix)\np.equals(new Point(1, 2));   \u002F\u002F true — value-based\n```\n\nThey're for transparent data aggregates (DTOs, value objects). Limits: records\nare `final`, can't extend a class (they implicitly extend `Record`), and all\nstate is in the header — you can still add a **compact constructor** for\nvalidation.\n",{"id":765,"difficulty":84,"q":766,"a":767},"nested-classes","What are the types of nested classes in Java?","- **Static nested class** — declared `static`; no link to an outer instance, a\n  namespaced helper.\n- **Inner (non-static) class** — holds an implicit reference to its enclosing\n  instance; can access its outer fields.\n- **Local class** — declared inside a method.\n- **Anonymous class** — an unnamed inner class created and instantiated at once.\n\n```java\nclass Outer {\n  static class Helper { }            \u002F\u002F static nested\n  class Inner { }                    \u002F\u002F inner — needs an Outer instance\n  Runnable r = new Runnable() {      \u002F\u002F anonymous\n    public void run() { }\n  };\n}\n```\n\nGotcha: a non-static inner class keeps the outer object alive (potential memory\nleak), so prefer `static` nested classes unless you actually need the enclosing\ninstance.\n",{"id":769,"difficulty":63,"q":770,"a":771},"object-equality-identity","What is the difference between identity, equality and equivalence?","- **Identity** — `a == b`: are they the *same object* in memory?\n- **Equality** — `a.equals(b)`: are they *logically the same value*, per the\n  class's definition?\n- Some classes also expose **ordering equivalence** via `compareTo == 0`.\n\n```java\nString a = new String(\"x\"), b = new String(\"x\");\na == b;            \u002F\u002F false (identity)\na.equals(b);       \u002F\u002F true  (equality)\n\nBigDecimal x = new BigDecimal(\"1.0\"), y = new BigDecimal(\"1.00\");\nx.equals(y);       \u002F\u002F false! (scale differs)\nx.compareTo(y) == 0; \u002F\u002F true  (numeric equivalence)\n```\n\n`BigDecimal` is the classic gotcha where `equals` and `compareTo` disagree.\n",{"id":773,"difficulty":84,"q":774,"a":775},"covariant-return","What is a covariant return type?","When overriding, the subclass method may return a **subtype** of the\nsuperclass method's return type — a covariant return. It lets overrides return\nmore specific types without a cast.\n\n```java\nclass Animal { Animal reproduce() { return new Animal(); } }\nclass Dog extends Animal {\n  @Override Dog reproduce() { return new Dog(); } \u002F\u002F narrower return — legal\n}\nDog puppy = new Dog().reproduce(); \u002F\u002F no cast needed\n```\n\nCommon in builder patterns and `clone()` overrides. (Parameters, by contrast,\nare *not* covariant — changing a parameter type makes it an overload, not an\noverride.)\n",{"id":777,"difficulty":84,"q":778,"a":779},"static-vs-dynamic-binding","What is the difference between static and dynamic binding?","**Static binding** is resolved by the compiler from the **declared type** —\nused for `static`, `private`, `final`, and overloaded methods, plus fields.\n**Dynamic binding** is resolved at runtime from the **actual object type** —\nused for overridden instance methods (virtual dispatch).\n\n```java\nclass A { static void s() { } void v() { } int f = 1; }\nclass B extends A { static void s() { } @Override void v() { } int f = 2; }\n\nA x = new B();\nx.v();   \u002F\u002F B.v()  — dynamic binding (overridden)\nx.s();   \u002F\u002F A.s()  — static binding (hidden, by declared type)\nx.f;     \u002F\u002F 1      — fields are static-bound, not polymorphic\n```\n\nKey insight: **fields and static methods are *hidden*, not overridden** — they\nbind to the declared type, which is a classic trick question.\n",{"id":781,"difficulty":84,"q":782,"a":783},"immutable-class","How do you design an immutable class?","Make the state impossible to change after construction:\n\n1. Mark the class `final` (no subclass can add mutability).\n2. Make all fields `private final`.\n3. Set everything in the constructor; provide **no setters**.\n4. **Defensively copy** mutable fields in and out (don't leak internal refs).\n\n```java\nfinal class Range {\n  private final int[] bounds;\n  Range(int[] bounds) { this.bounds = bounds.clone(); } \u002F\u002F copy in\n  int[] bounds() { return bounds.clone(); }             \u002F\u002F copy out\n}\n```\n\nImmutables are inherently **thread-safe**, cacheable, and safe as map keys —\n`String`, `Integer`, and `LocalDate` are all built this way.\n",{"id":785,"difficulty":63,"q":786,"a":787},"this-vs-super-ctor","Can a constructor call both this() and super()?","No. Both `this(...)` (chain to another constructor in the same class) and\n`super(...)` (chain to the parent) must be the **first statement** in a\nconstructor — and there can only be one first statement, so you use **at most\none** of them.\n\n```java\nclass Base { Base(int n) { } }\nclass Sub extends Base {\n  Sub() { this(5); }          \u002F\u002F delegates within Sub...\n  Sub(int n) { super(n); }    \u002F\u002F ...which then reaches super\n}\n```\n\nThe pattern is to funnel overloaded constructors through `this(...)` down to one\n\"primary\" constructor that finally calls `super(...)`.\n",{"id":789,"difficulty":63,"q":790,"a":791},"object-creation","What are the ways to create an object in Java?","- **`new`** — the normal path, invokes a constructor.\n- **Factory method** — e.g. `List.of()`, `Integer.valueOf()`, your own\n  `Builder.build()`.\n- **`Class.getDeclaredConstructor().newInstance()`** — reflection.\n- **`clone()`** — copy an existing object.\n- **Deserialization** — reconstruct from bytes (bypasses constructors).\n\n```java\nUser a = new User();                          \u002F\u002F new\nList\u003CInteger> b = List.of(1, 2);              \u002F\u002F factory\nUser c = User.class.getDeclaredConstructor().newInstance(); \u002F\u002F reflection\n```\n\nNote that reflection and deserialization can create objects **without running a\nconstructor**, which is why immutability\u002Fsingletons sometimes need extra guards.\n",{"id":793,"difficulty":71,"q":794,"a":795},"ducktyping-isa-hasa","What is the difference between an is-a and a has-a relationship?","- **is-a** -> inheritance. A `Car` *is a* `Vehicle` -> `class Car extends\n  Vehicle`.\n- **has-a** -> composition\u002Faggregation. A `Car` *has an* `Engine` -> the `Car`\n  holds an `Engine` field.\n\n```java\nclass Engine { }\nclass Car extends Vehicle {   \u002F\u002F is-a Vehicle\n  private final Engine engine = new Engine(); \u002F\u002F has-a Engine\n}\n```\n\nModeling tip: if you can't truthfully say \"X is a Y,\" don't use inheritance —\nreach for has-a (composition) instead. Misusing is-a (e.g. `Stack extends\nVector`) is a classic design smell.\n",{"id":797,"difficulty":84,"q":798,"a":799},"method-hiding","What is method hiding and how does it differ from overriding?","When a subclass declares a `static` method with the same signature as a parent\n`static` method, it **hides** rather than overrides it. The version called\ndepends on the **declared (compile-time) type**, not the runtime object — the\nopposite of overriding.\n\n```java\nclass A { static String who() { return \"A\"; } }\nclass B extends A { static String who() { return \"B\"; } }\n\nA ref = new B();\nref.who();   \u002F\u002F \"A\"  — static method, resolved by declared type (hiding)\n\u002F\u002F If who() were an instance method, this would be \"B\" (overriding)\n```\n\nBecause of this confusion, call static methods on the **class** (`A.who()`),\nnever through an instance reference.\n",{"id":801,"difficulty":63,"q":802,"a":803},"interface-vs-abstract-when","Can a class implement multiple interfaces with the same method?","Yes. If two interfaces declare the **same abstract** method, one implementation\nsatisfies both. But if they provide **conflicting `default`** methods, the class\n**must override** to break the tie, optionally delegating with\n`Interface.super.method()`.\n\n```java\ninterface A { default String hi() { return \"A\"; } }\ninterface B { default String hi() { return \"B\"; } }\n\nclass C implements A, B {\n  @Override public String hi() {\n    return A.super.hi();   \u002F\u002F explicitly choose A's default\n  }\n}\n```\n\nThis is Java's controlled answer to the multiple-inheritance \"diamond problem\":\nmultiple *types* are allowed, but conflicting *behavior* must be resolved\nexplicitly.\n",{"id":805,"difficulty":63,"q":806,"a":807},"polymorphism-collections","How does polymorphism enable programming to an interface?","By declaring variables and parameters as the **interface\u002Fsupertype**, your code\nworks with *any* implementation — the runtime calls the actual object's\nmethods. This decouples callers from concrete classes.\n\n```java\nvoid process(List\u003CString> items) { }   \u002F\u002F accepts ArrayList, LinkedList, List.of...\nList\u003CString> list = new ArrayList\u003C>();  \u002F\u002F swap impl freely\n\u002F\u002F list = new LinkedList\u003C>();           \u002F\u002F no caller changes needed\n```\n\n\"Program to an interface, not an implementation\" — depend on `List`, `Map`,\n`Collection`, not `ArrayList`\u002F`HashMap`. It makes code testable (inject fakes)\nand flexible (change implementations without ripple effects).\n",{"id":809,"difficulty":63,"q":810,"a":811},"cohesion-coupling","What are cohesion and coupling?","- **Cohesion** — how focused a class is on a single responsibility. **High\n  cohesion is good**: a `UserValidator` that only validates users.\n- **Coupling** — how dependent classes are on each other's internals. **Low\n  coupling is good**: classes interact through small, stable interfaces.\n\n```java\n\u002F\u002F low coupling: depends on an interface, not a concrete logger\nclass OrderService {\n  private final Logger log;            \u002F\u002F injected abstraction\n  OrderService(Logger log) { this.log = log; }\n}\n```\n\nThe goal of good OO design is **high cohesion, low coupling** — classes that do\none thing well and lean on each other as little as possible, which makes systems\neasier to change and test.\n",{"id":813,"difficulty":84,"q":814,"a":815},"solid","What do the SOLID principles stand for?","Five OO design principles for maintainable code:\n\n- **S** — Single Responsibility: a class has one reason to change.\n- **O** — Open\u002FClosed: open for extension, closed for modification.\n- **L** — Liskov Substitution: subtypes must be usable wherever their base is.\n- **I** — Interface Segregation: prefer small, specific interfaces over fat ones.\n- **D** — Dependency Inversion: depend on abstractions, not concretions.\n\n```java\n\u002F\u002F Dependency Inversion: high-level code depends on an interface\ninterface Repository { void save(Order o); }\nclass OrderService {\n  private final Repository repo;       \u002F\u002F not a concrete DB class\n  OrderService(Repository repo) { this.repo = repo; }\n}\n```\n\nLiskov is the one interviewers probe most: a subclass that throws on, or\nweakens, an inherited method (the `Square extends Rectangle` problem) violates\nit.\n",{"description":61},"Java OOP interview questions — the four pillars, inheritance vs composition, abstract classes vs interfaces, overloading vs overriding, polymorphism, the equals\u002FhashCode contract, records and enums.","java\u002Ffundamentals\u002Foop","Object-Oriented Programming","unDNeaf0bQsd2Gz0CAYtw3utDO8XyOVtZREhMpXE9oI",{"id":822,"title":823,"body":824,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":828,"navigation":66,"order":12,"path":829,"questions":830,"related":207,"seo":959,"seoDescription":960,"stem":961,"subtopic":823,"topic":962,"topicSlug":963,"updated":214,"__hash__":964},"qa\u002Fjavascript\u002Farrays\u002Farray-methods.md","Array Methods",{"type":58,"value":825,"toc":826},[],{"title":61,"searchDepth":22,"depth":22,"links":827},[],{},"\u002Fjavascript\u002Farrays\u002Farray-methods",[831,835,839,843,847,851,855,859,863,867,871,875,879,883,887,891,895,899,903,907,911,915,919,923,927,931,935,939,943,947,951,955],{"id":832,"difficulty":71,"q":833,"a":834},"map-basics","What does Array.prototype.map do?","**map** creates a **new array** by calling a callback on every element and\ncollecting the return values. It does not mutate the original and always\nreturns an array of the **same length**.\n\n```js\nconst nums = [1, 2, 3]\nconst doubled = nums.map(n => n * 2) \u002F\u002F [2, 4, 6]\nnums \u002F\u002F [1, 2, 3] — unchanged\n```\n\nA common pitfall is using `map` purely for side effects (logging, pushing\nelsewhere). If you don't use the returned array, use `forEach` instead — it\nsignals intent and avoids allocating a throwaway array.\n",{"id":836,"difficulty":71,"q":837,"a":838},"filter-basics","What does Array.prototype.filter do?","**filter** returns a **new array** containing only the elements for which the\ncallback returns a **truthy** value. Length is less than or equal to the\noriginal.\n\n```js\nconst nums = [1, 2, 3, 4]\nconst evens = nums.filter(n => n % 2 === 0) \u002F\u002F [2, 4]\n```\n\nGotcha: the predicate must return a boolean-ish value. Forgetting `return` in\na block body silently filters everything out, since `undefined` is falsy:\n\n```js\nnums.filter(n => { n % 2 === 0 }) \u002F\u002F [] — no return\n```\n",{"id":840,"difficulty":71,"q":841,"a":842},"foreach-basics","What is forEach used for and what does it return?","**forEach** runs a callback once per element for **side effects**. It always\nreturns **undefined** — you can't chain off it.\n\n```js\n[1, 2, 3].forEach(n => console.log(n))\n```\n\nTwo gotchas: you **cannot break** out of `forEach` (use a `for...of` or `some`\nif you need early exit), and it **skips holes** in sparse arrays. If you need\na transformed result, reach for `map` instead.\n",{"id":844,"difficulty":63,"q":845,"a":846},"reduce-basics","How does Array.prototype.reduce work?","**reduce** folds an array into a **single value** by threading an accumulator\nthrough a callback `(acc, cur) => newAcc`. You pass an **initial value** as the\nsecond argument.\n\n```js\nconst sum = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0) \u002F\u002F 10\n```\n\nPitfall: **omitting the initial value** makes reduce use the first element as\nthe seed and start at index 1 — and it **throws** on an empty array. Always\npass an explicit initial value unless you have a specific reason not to.\n",{"id":848,"difficulty":63,"q":849,"a":850},"reduce-no-initial","What happens if you call reduce without an initial value on an empty array?","It throws a **TypeError: Reduce of empty array with no initial value**. With no\nseed, reduce needs at least one element to start from.\n\n```js\n[].reduce((a, b) => a + b)    \u002F\u002F TypeError\n[].reduce((a, b) => a + b, 0) \u002F\u002F 0\n```\n\nThis is why supplying an initial value is a best practice — it makes the\noperation total (defined for all inputs) and pins down the accumulator's type.\n",{"id":852,"difficulty":63,"q":853,"a":854},"reduceright","What is reduceRight and when would you use it?","**reduceRight** is identical to `reduce` but processes elements from **right to\nleft**. It matters when the operation is **not associative** or when order of\ncomposition matters.\n\n```js\n\u002F\u002F function composition: f(g(h(x)))\nconst compose = (...fns) => x =>\n  fns.reduceRight((acc, fn) => fn(acc), x)\n\nconst f = compose(n => n + 1, n => n * 2)\nf(3) \u002F\u002F 7  -> (3*2)+1\n```\n\nFor plain addition the direction is irrelevant; for string building, division,\nor composition it changes the result.\n",{"id":856,"difficulty":71,"q":857,"a":858},"some-every","What is the difference between some and every?","**some** returns `true` if **at least one** element passes the predicate;\n**every** returns `true` only if **all** elements pass. Both **short-circuit**.\n\n```js\n[1, 2, 3].some(n => n > 2)  \u002F\u002F true  (stops at 3)\n[1, 2, 3].every(n => n > 0) \u002F\u002F true\n[1, 2, 3].every(n => n > 1) \u002F\u002F false (stops at 1)\n```\n\nEdge case: `every` on an **empty array** returns `true` (vacuous truth) and\n`some` returns `false`. This trips people up in validation code.\n",{"id":860,"difficulty":71,"q":861,"a":862},"find-findindex","What is the difference between find and findIndex?","**find** returns the **first element** that satisfies the predicate, or\n`undefined`. **findIndex** returns its **index**, or `-1`.\n\n```js\nconst users = [{ id: 1 }, { id: 2 }]\nusers.find(u => u.id === 2)      \u002F\u002F { id: 2 }\nusers.findIndex(u => u.id === 2) \u002F\u002F 1\nusers.find(u => u.id === 9)      \u002F\u002F undefined\n```\n\nUse `find` when you want the object itself; use `findIndex` when you need the\nposition (e.g. to splice or replace it).\n",{"id":864,"difficulty":63,"q":865,"a":866},"findlast","What do findLast and findLastIndex do?","They mirror `find`\u002F`findIndex` but search from the **end** of the array\nbackward, returning the **last** matching element or its index.\n\n```js\nconst nums = [1, 5, 3, 5, 2]\nnums.findLast(n => n === 5)      \u002F\u002F 5  (the second 5)\nnums.findLastIndex(n => n === 5) \u002F\u002F 3\n```\n\nBefore these (ES2023) you'd reverse a copy or loop manually. They avoid an\nextra `[...arr].reverse().find(...)` allocation and keep the original index\nmeaningful.\n",{"id":868,"difficulty":71,"q":869,"a":870},"indexof-vs-find","When should you use find versus indexOf?","Use **indexOf** for **primitive equality** (it uses strict `===`), and **find**\nwhen you need a **predicate** (matching by a property or condition).\n\n```js\n[10, 20, 30].indexOf(20)              \u002F\u002F 1\nusers.find(u => u.name === 'Ann')     \u002F\u002F predicate match\n```\n\n`indexOf` can't match objects by content, only by reference, so for arrays of\nobjects you almost always want `find`\u002F`findIndex`.\n",{"id":872,"difficulty":63,"q":873,"a":874},"flat","What does Array.prototype.flat do?","**flat** returns a **new array** with sub-array elements concatenated up to a\ngiven **depth** (default `1`). It does not mutate.\n\n```js\n[1, [2, [3, [4]]]].flat()        \u002F\u002F [1, 2, [3, [4]]]\n[1, [2, [3, [4]]]].flat(2)       \u002F\u002F [1, 2, 3, [4]]\n[1, [2, [3]]].flat(Infinity)     \u002F\u002F [1, 2, 3] fully flatten\n```\n\nUse `flat(Infinity)` for arbitrarily nested structures. It also removes empty\nslots in sparse arrays as a side effect.\n",{"id":876,"difficulty":63,"q":877,"a":878},"flatmap","What is flatMap and how does it differ from map then flat?","**flatMap** maps each element then flattens the result by **one level**, in a\nsingle pass. It's equivalent to `map(...).flat()` but more efficient and\nexpressive.\n\n```js\nconst sentences = ['a b', 'c d']\nsentences.flatMap(s => s.split(' ')) \u002F\u002F ['a', 'b', 'c', 'd']\n```\n\nIt only flattens **one level**. A neat trick: returning `[]` from the callback\n**drops** an element, letting flatMap act as a combined map+filter.\n",{"id":880,"difficulty":63,"q":881,"a":882},"array-from","What does Array.from do?","**Array.from** creates a real array from any **iterable** or **array-like**\nobject (one with a `length` and indexed keys). It accepts an optional mapping\nfunction as a second argument.\n\n```js\nArray.from('abc')              \u002F\u002F ['a', 'b', 'c']\nArray.from(new Set([1, 1, 2])) \u002F\u002F [1, 2]\nArray.from({ length: 3 }, (_, i) => i) \u002F\u002F [0, 1, 2]\n```\n\nThe mapping form is handy for generating sequences and avoids creating an\nintermediate array, unlike `[...iterable].map(fn)`.\n",{"id":884,"difficulty":71,"q":885,"a":886},"array-of","Why does Array.of exist when we have the Array constructor?","**Array.of** creates an array from its arguments **consistently**, fixing a\nquirk of `new Array()`: a single numeric argument is treated as a **length**,\nnot an element.\n\n```js\nArray(3)      \u002F\u002F [ \u003C3 empty items> ] — length 3\nArray.of(3)   \u002F\u002F [3]\nArray(1, 2)   \u002F\u002F [1, 2] — but inconsistent with Array(3)\nArray.of(1, 2)\u002F\u002F [1, 2]\n```\n\n`Array.of` always treats arguments as elements, so it's safer in generic code.\n",{"id":888,"difficulty":63,"q":889,"a":890},"entries-keys-values","What do entries, keys, and values return on an array?","They return **array iterators**, not arrays. `keys()` yields indices,\n`values()` yields elements, and `entries()` yields `[index, value]` pairs.\n\n```js\nconst arr = ['a', 'b']\nfor (const [i, v] of arr.entries()) {\n  console.log(i, v) \u002F\u002F 0 'a', then 1 'b'\n}\n[...arr.keys()]   \u002F\u002F [0, 1]\n[...arr.values()] \u002F\u002F ['a', 'b']\n```\n\n`entries()` is the clean way to get the index inside a `for...of` loop without\na manual counter.\n",{"id":892,"difficulty":63,"q":893,"a":894},"chaining","How does method chaining work with array methods?","Because **map**, **filter**, **slice**, and friends each return a **new array**,\nyou can chain them into a readable pipeline.\n\n```js\nconst result = users\n  .filter(u => u.active)\n  .map(u => u.name)\n  .sort() \u002F\u002F active users' names, sorted\n```\n\nTradeoff: each step allocates a new array and does a full pass. For huge arrays\nor hot paths a single `reduce` (or a plain loop) can avoid the intermediate\narrays, at the cost of readability.\n",{"id":896,"difficulty":84,"q":897,"a":898},"reduce-to-object","How do you use reduce to build an object from an array?","Seed the accumulator with `{}` and assign keys as you go. This is the canonical\nway to **index** a list by id.\n\n```js\nconst users = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }]\nconst byId = users.reduce((acc, u) => {\n  acc[u.id] = u\n  return acc\n}, {}) \u002F\u002F { 1: {...}, 2: {...} }\n```\n\nFor this exact case, `Object.fromEntries(users.map(u => [u.id, u]))` is often\nclearer. Reserve reduce-to-object for logic that doesn't fit a simple map.\n",{"id":900,"difficulty":84,"q":901,"a":902},"reduce-grouping","How do you group array items by a key?","Use **reduce** to accumulate into buckets, initializing each bucket lazily.\n\n```js\nconst items = [{ type: 'a', v: 1 }, { type: 'b', v: 2 }, { type: 'a', v: 3 }]\nconst grouped = items.reduce((acc, item) => {\n  (acc[item.type] ??= []).push(item) \u002F\u002F create bucket then push\n  return acc\n}, {})\n\u002F\u002F { a: [{a,1},{a,3}], b: [{b,2}] }\n```\n\nModern engines also offer **Object.groupBy(items, item => item.type)**, which\ndoes exactly this without the boilerplate.\n",{"id":904,"difficulty":63,"q":905,"a":906},"reduce-flatten","How can reduce flatten an array of arrays?","Concatenate each sub-array into an accumulator:\n\n```js\nconst nested = [[1, 2], [3], [4, 5]]\nconst flat = nested.reduce((acc, sub) => acc.concat(sub), []) \u002F\u002F [1,2,3,4,5]\n```\n\nIn practice prefer the dedicated `nested.flat()` — it's clearer and faster. The\nreduce version is mostly useful as an interview demonstration of how flattening\nworks under the hood, or when you need custom merge logic per chunk.\n",{"id":908,"difficulty":71,"q":909,"a":910},"map-index","How do you access the index inside map, filter, or forEach?","Every iteration callback receives `(element, index, array)`. The second\nparameter is the index.\n\n```js\n['a', 'b', 'c'].map((char, i) => `${i}:${char}`) \u002F\u002F ['0:a', '1:b', '2:c']\n```\n\nGotcha: passing a method like `arr.map(parseInt)` breaks because `parseInt`\nreceives the index as its radix argument: `['1','2','3'].map(parseInt)` gives\n`[1, NaN, NaN]`. Wrap it: `arr.map(Number)` or `arr.map(s => parseInt(s, 10))`.\n",{"id":912,"difficulty":71,"q":913,"a":914},"map-vs-foreach","When should you choose map over forEach?","Choose **map** when you want a **transformed array** back; choose **forEach**\nwhen you only need **side effects** and ignore the return value.\n\n```js\nconst upper = names.map(n => n.toUpperCase()) \u002F\u002F need result\nnames.forEach(n => console.log(n))            \u002F\u002F side effect only\n```\n\nUsing `map` without consuming the result is a code smell — it implies a\ntransformation that's thrown away, confusing readers and wasting an allocation.\n",{"id":916,"difficulty":84,"q":917,"a":918},"chaining-vs-loop","What are the performance tradeoffs of chaining versus a single loop?","Each chained method (`filter().map()`) does a **full pass** and **allocates a\nnew array**. A single `for` loop or one `reduce` does one pass with no\nintermediate arrays.\n\n```js\n\u002F\u002F 2 passes, 2 arrays\narr.filter(x => x > 0).map(x => x * 2)\n\u002F\u002F 1 pass, 1 array\narr.reduce((acc, x) => (x > 0 && acc.push(x * 2), acc), [])\n```\n\nFor typical data sizes the difference is negligible and readability wins. Only\nfuse into a loop when profiling shows it matters.\n",{"id":920,"difficulty":71,"q":921,"a":922},"chaining-empty","What happens when you chain methods on an empty array?","Iteration methods on an empty array simply **don't call the callback** and\nreturn an empty (or seeded) result — no errors.\n\n```js\n[].map(x => x.boom)        \u002F\u002F [] — callback never runs\n[].filter(Boolean)         \u002F\u002F []\n[].reduce((a, b) => a + b) \u002F\u002F throws — no initial value\n```\n\nThe only landmine is `reduce` with no initial value, which throws on empty\ninput. Everything else degrades gracefully to an empty result.\n",{"id":924,"difficulty":63,"q":925,"a":926},"which-method","How do you decide which iteration method to use?","Match the method to the **shape of the result** you want:\n\n```text\ntransform each -> map\nkeep a subset -> filter\none value -> reduce\na single match -> find \u002F findIndex\nyes\u002Fno across all -> some \u002F every\nside effects only -> forEach (or for...of)\n```\n\nPicking the right method makes intent obvious. Reaching for `reduce` when\n`map` or `filter` fits is a common over-engineering mistake.\n",{"id":928,"difficulty":63,"q":929,"a":930},"chaining-readability","How can you keep long method chains readable?","Put **each step on its own line**, name intermediate results when a chain gets\nlong, and keep callbacks small (extract named functions for complex logic).\n\n```js\nconst activeNames = users\n  .filter(isActive)      \u002F\u002F named predicate\n  .map(u => u.name)\n  .sort(byAlpha)\n```\n\nA chain longer than 3-4 steps, or with multi-line callbacks, is often clearer\nsplit into named variables. Optimize for the next reader, not for fewer lines.\n",{"id":932,"difficulty":71,"q":933,"a":934},"copy-with-map","Does map produce a deep or shallow copy?","`map` produces a **new array**, but the elements are the **same references** for\nobjects — it's a **shallow** transform.\n\n```js\nconst arr = [{ n: 1 }]\nconst copy = arr.map(o => o)\ncopy[0].n = 99\narr[0].n \u002F\u002F 99 — same object reference\n```\n\nTo copy each object too, map to a new object: `arr.map(o => ({ ...o }))`. For\ndeeply nested data, `structuredClone` per element is safer.\n",{"id":936,"difficulty":84,"q":937,"a":938},"side-effects-in-map","Why are side effects inside map considered an anti-pattern?","`map` is meant to be a **pure transformation**: input array in, new array out.\nMutating external state or other elements inside the callback makes the code\nhard to reason about and order-dependent.\n\n```js\nlet total = 0\narr.map(x => { total += x; return x }) \u002F\u002F hidden side effect\n```\n\nUse `forEach`\u002F`for...of` for side effects and `reduce` for accumulation. Keep\n`map` pure so chains stay predictable and refactor-safe.\n",{"id":940,"difficulty":63,"q":941,"a":942},"chaining-find-after-filter","Why is filter().find() sometimes wasteful, and what's better?","`filter` walks the **entire array** building a new one, then `find` walks again.\nIf you only need the first match, `find` alone short-circuits on the first hit.\n\n```js\narr.filter(x => x > 10)[0]   \u002F\u002F full pass + array allocation\narr.find(x => x > 10)        \u002F\u002F stops at first match\n```\n\nSimilarly, prefer `some` over `filter(...).length > 0`. Choosing a\nshort-circuiting method avoids unnecessary work on large arrays.\n",{"id":944,"difficulty":63,"q":945,"a":946},"reduce-max","How do you find the maximum value with reduce?","Thread the running maximum through the accumulator:\n\n```js\nconst max = [3, 7, 2, 9, 4].reduce((m, n) => (n > m ? n : m), -Infinity)\n\u002F\u002F 9\n```\n\nSeeding with `-Infinity` keeps it correct even when all values are negative.\nFor plain numbers `Math.max(...arr)` is shorter, but it risks a stack overflow\non very large arrays — reduce stays safe there.\n",{"id":948,"difficulty":71,"q":949,"a":950},"array-isarray","How do you reliably check if a value is an array?","Use **Array.isArray**. `typeof []` returns `'object'`, so it can't distinguish\narrays from other objects.\n\n```js\nArray.isArray([1, 2]) \u002F\u002F true\nArray.isArray('ab')   \u002F\u002F false\ntypeof []             \u002F\u002F 'object' — useless here\n```\n\n`Array.isArray` also works correctly across **iframes\u002Frealms**, where\n`instanceof Array` can fail because each realm has its own `Array` constructor.\n",{"id":952,"difficulty":84,"q":953,"a":954},"foreach-async","Why does forEach not work well with async\u002Fawait?","`forEach` **ignores the promise** returned by an async callback, so it does not\nwait — the loop finishes before any async work completes.\n\n```js\nids.forEach(async id => { await save(id) }) \u002F\u002F doesn't await\n\u002F\u002F \"done\" logs before saves finish\n\nfor (const id of ids) { await save(id) }    \u002F\u002F sequential\nawait Promise.all(ids.map(id => save(id)))  \u002F\u002F parallel\n```\n\nUse a `for...of` loop for sequential awaits, or `map` + `Promise.all` to run\nthem concurrently and await the lot.\n",{"id":956,"difficulty":63,"q":957,"a":958},"callback-third-arg","What is the third argument passed to array iteration callbacks?","It's the **array being iterated** itself. It lets a callback reference\nneighboring elements without closing over an outer variable.\n\n```js\n[10, 20, 30].map((val, i, arr) =>\n  i > 0 ? val - arr[i - 1] : 0\n) \u002F\u002F [0, 10, 10] — differences\n```\n\nIt's rarely needed, but handy for look-ahead\u002Flook-behind logic and for writing\ngeneric helpers that don't depend on an external reference to the array.\n",{"description":61},"JavaScript array method interview questions — map, filter, reduce, forEach, some, every, find, flat, flatMap, Array.from and how to chain iteration methods effectively.","javascript\u002Farrays\u002Farray-methods","Arrays & Iteration","arrays","Elw--T-gcVD4zuO2afQStkL-UYCKrtemiCrb2WELzjs",{"id":966,"title":967,"body":968,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":972,"navigation":66,"order":40,"path":973,"questions":974,"related":207,"seo":1098,"seoDescription":1099,"stem":1100,"subtopic":1101,"topic":962,"topicSlug":963,"updated":214,"__hash__":1102},"qa\u002Fjavascript\u002Farrays\u002Fdestructuring-spread.md","Destructuring Spread",{"type":58,"value":969,"toc":970},[],{"title":61,"searchDepth":22,"depth":22,"links":971},[],{},"\u002Fjavascript\u002Farrays\u002Fdestructuring-spread",[975,979,983,986,990,994,998,1002,1006,1010,1014,1018,1022,1026,1030,1034,1038,1042,1046,1050,1054,1058,1062,1066,1070,1074,1078,1082,1086,1090,1094],{"id":976,"difficulty":71,"q":977,"a":978},"array-destructuring-basics","What is array destructuring?","**Array destructuring** unpacks values from an array into distinct\nvariables by **position**, using a pattern on the left of `=`.\n\n```js\nconst [first, second] = [10, 20]\nfirst   \u002F\u002F 10\nsecond  \u002F\u002F 20  assigned by index, not name\n```\n\nIt works on any iterable, not just arrays — strings, Sets, Maps, and\ngenerators all destructure positionally.\n",{"id":980,"difficulty":71,"q":981,"a":982},"skipping-elements","How do you skip elements while destructuring?","Leave an **empty slot** (just a comma) for each element you want to skip.\n\n```js\nconst [, , third] = ['a', 'b', 'c']\nthird   \u002F\u002F 'c'  first two skipped\n```\n\nEach comma consumes one position. It's readable for one skip; for several,\nconsider naming with an underscore convention or indexing directly to keep\nit clear.\n",{"id":568,"difficulty":71,"q":984,"a":985},"How do default values work in array destructuring?","A default applies only when the matched value is **`undefined`** (not for\n`null` or other falsy values).\n\n```js\nconst [a = 1, b = 2] = [10]\na  \u002F\u002F 10\nb  \u002F\u002F 2   undefined -> default\n\nconst [c = 5] = [null]\nc  \u002F\u002F null  null is not undefined, no default\n```\n\nMissing array positions read as `undefined`, which is exactly why defaults\nkick in there.\n",{"id":987,"difficulty":71,"q":988,"a":989},"swapping-variables","How do you swap two variables with destructuring?","Build an array literal on the right and destructure it on the left — no\ntemp variable needed.\n\n```js\nlet a = 1, b = 2\n[a, b] = [b, a]\na  \u002F\u002F 2\nb  \u002F\u002F 1\n```\n\nThe right side is fully evaluated before assignment, so the swap is\natomic. Watch out: if the previous line lacks a semicolon, the leading\n`[` can be parsed as indexing — start the line with a semicolon if unsure.\n",{"id":991,"difficulty":63,"q":992,"a":993},"nested-destructuring","How do you destructure nested arrays?","Mirror the structure with nested patterns.\n\n```js\nconst [[a, b], [c]] = [[1, 2], [3]]\na  \u002F\u002F 1\nb  \u002F\u002F 2\nc  \u002F\u002F 3\n```\n\nYou can mix in defaults and skips at any level. Deeply nested patterns get\nhard to read fast — destructure one level and name intermediates if it\nstops being obvious.\n",{"id":995,"difficulty":63,"q":996,"a":997},"rest-element","What is the rest element in array destructuring?","A trailing **`...name`** collects all remaining elements into a **new\narray**.\n\n```js\nconst [head, ...tail] = [1, 2, 3, 4]\nhead  \u002F\u002F 1\ntail  \u002F\u002F [2, 3, 4]  a real array\n```\n\nThe rest element must be **last** — `const [...rest, last]` is a\nSyntaxError. It always produces an array, even if empty.\n",{"id":999,"difficulty":63,"q":1000,"a":1001},"rest-vs-spread","What's the difference between rest and spread, since both use ...?","Same syntax, opposite jobs. **Rest** *collects* multiple elements into one\narray (on the left, in a pattern). **Spread** *expands* one iterable into\nmultiple elements (on the right, in a literal or call).\n\n```js\nconst [first, ...rest] = arr      \u002F\u002F rest: gather\nconst copy = [...arr]             \u002F\u002F spread: expand\n```\n\nPosition is the tell: `...` on the binding side = rest; `...` on the value\nside = spread.\n",{"id":1003,"difficulty":71,"q":1004,"a":1005},"spread-copy","How do you copy an array with spread, and what kind of copy is it?","`[...arr]` produces a **shallow copy** — a new top-level array whose\nelements are the same references.\n\n```js\nconst a = [{ x: 1 }, 2]\nconst b = [...a]\nb === a       \u002F\u002F false  new array\nb[0] === a[0] \u002F\u002F true   inner object still shared\n```\n\nFor nested data you need a deep copy: `structuredClone(a)`.\n",{"id":1007,"difficulty":71,"q":1008,"a":1009},"spread-merge","How do you concatenate arrays with spread?","Spread each array into a new literal, in the order you want.\n\n```js\nconst merged = [...a, ...b, ...c]   \u002F\u002F flat concatenation\nconst withExtras = [0, ...a, 99]    \u002F\u002F insert around them\n```\n\nIt reads more clearly than `a.concat(b, c)` and lets you interleave\nindividual elements, though `concat` can be marginally faster for very\nlarge arrays.\n",{"id":1011,"difficulty":63,"q":1012,"a":1013},"spread-vs-concat","When would you use concat instead of spread?","Functionally similar for merging, but **`concat`** has two edge behaviors\nspread doesn't: it can append non-array values directly, and it's often\nfaster for huge arrays since the engine doesn't iterate element-by-element.\n\n```js\n[1, 2].concat(3, [4, 5])   \u002F\u002F [1, 2, 3, 4, 5]  mixes values and arrays\n[...[1,2], 3, ...[4,5]]    \u002F\u002F same result via spread\n```\n\nUse spread for readability and interleaving; reach for `concat` in hot\npaths over large arrays.\n",{"id":1015,"difficulty":63,"q":1016,"a":1017},"spread-iterables","What can you spread besides arrays?","Anything **iterable**: strings, `Set`, `Map`, `arguments`, NodeLists,\ngenerators.\n\n```js\n[...'abc']            \u002F\u002F ['a', 'b', 'c']  string -> chars\n[...new Set([1,1,2])] \u002F\u002F [1, 2]\n[...map.entries()]    \u002F\u002F [[k, v], ...]\n```\n\nPlain objects are **not** iterable, so `[...{a:1}]` throws. Use\n`Object.values`\u002F`entries` to turn an object into an iterable first.\n",{"id":1019,"difficulty":63,"q":1020,"a":1021},"spread-string-chars","Why is [...str] safer than str.split('') for splitting characters?","Spread iterates by **code point** (respecting surrogate pairs), while\n`split('')` splits by UTF-16 **code unit**, breaking emoji and other\nastral characters.\n\n```js\n[...'a😀b']          \u002F\u002F ['a', '😀', 'b']  ✅\n'a😀b'.split('')     \u002F\u002F ['a', '\\ud83d', '\\ude00', 'b']  ❌ broken\n```\n\nPrefer spread (or `Array.from`) whenever input might contain non-BMP\ncharacters.\n",{"id":1023,"difficulty":71,"q":1024,"a":1025},"spread-function-args","How do you pass an array as separate arguments?","Spread it in the call site — it replaces the old `Function.prototype.apply`\npattern.\n\n```js\nconst nums = [5, 1, 9]\nMath.max(...nums)        \u002F\u002F 9\nMath.max.apply(null, nums) \u002F\u002F old way\n```\n\nYou can also mix fixed and spread args: `fn(a, ...rest, b)`. One caveat:\nspreading a very large array (100k+) can hit argument-count limits — loop\nor `reduce` instead.\n",{"id":1027,"difficulty":63,"q":1028,"a":1029},"rest-parameters-vs-destructuring","How does a rest element differ from rest parameters?","They look identical but live in different places. A **rest element**\nappears in a destructuring pattern and gathers leftover array items; **rest\nparameters** appear in a function signature and gather leftover arguments.\n\n```js\nconst [a, ...rest] = arr            \u002F\u002F rest element\nfunction f(first, ...others) {}     \u002F\u002F rest parameters\n```\n\nBoth produce real arrays (unlike the old `arguments` object), and both must\nbe last.\n",{"id":1031,"difficulty":63,"q":1032,"a":1033},"destructure-in-params","How do you destructure an array in a function parameter?","Put the pattern directly in the parameter list — handy for functions\nreceiving coordinate pairs or `Object.entries` items.\n\n```js\nfunction dist([x1, y1], [x2, y2]) {\n  return Math.hypot(x2 - x1, y2 - y1)\n}\ndist([0, 0], [3, 4])   \u002F\u002F 5\n```\n\nAdd a default for the whole parameter (`= []`) if it might be missing,\notherwise destructuring `undefined` throws.\n",{"id":1035,"difficulty":63,"q":1036,"a":1037},"destructure-in-loops","How is array destructuring used in for...of loops?","Destructure each iterated item inline — extremely common with\n`entries()` and `Object.entries`.\n\n```js\nfor (const [i, value] of arr.entries()) {\n  console.log(i, value)   \u002F\u002F index and value\n}\nfor (const [key, val] of Object.entries(obj)) { \u002F* ... *\u002F }\n```\n\nIt keeps the loop body clean versus indexing into a pair with `[0]`\u002F`[1]`.\n",{"id":1039,"difficulty":63,"q":1040,"a":1041},"swap-array-elements","How do you swap two elements within an array?","Destructure the two positions on the left and provide them swapped on the\nright.\n\n```js\nconst a = [1, 2, 3, 4]\n;[a[1], a[3]] = [a[3], a[1]]\na   \u002F\u002F [1, 4, 3, 2]\n```\n\nAs with variable swaps, lead with a semicolon when the previous statement\ndoesn't end in one, so `[` isn't read as indexing.\n",{"id":1043,"difficulty":84,"q":1044,"a":1045},"default-from-other","Can a destructuring default reference an earlier bound variable?","Yes — defaults are evaluated **left to right**, so a later default can use\nan already-assigned earlier one.\n\n```js\nconst [a = 1, b = a * 2] = []\na  \u002F\u002F 1\nb  \u002F\u002F 2   b's default used a\n```\n\nReferencing a variable that hasn't been bound *yet* (to its right) throws a\ntemporal-dead-zone error. Keep dependencies left-to-right.\n",{"id":1047,"difficulty":63,"q":1048,"a":1049},"destructure-undefined","What happens when you destructure null or undefined?","Both throw a **TypeError**, because destructuring tries to read the\niterator (`Symbol.iterator`) off the value.\n\n```js\nconst [a] = null        \u002F\u002F TypeError\nconst [b] = undefined   \u002F\u002F TypeError\nconst [c] = []          \u002F\u002F c is undefined (empty but iterable)\n```\n\nGuard with a default at the source: `const [c] = maybeArr ?? []`.\n",{"id":1051,"difficulty":84,"q":1052,"a":1053},"spread-shallow-pitfall","What's the classic bug with spreading nested arrays?","People assume `[...arr]` deep-copies, but inner arrays\u002Fobjects stay shared,\nso mutating them mutates the \"copy\" too.\n\n```js\nconst matrix = [[1], [2]]\nconst copy = [...matrix]\ncopy[0].push(99)\nmatrix[0]   \u002F\u002F [1, 99]  original changed\n```\n\nFor grids\u002Fnested structures use `matrix.map(row => [...row])` (one level)\nor `structuredClone(matrix)` (any depth).\n",{"id":1055,"difficulty":63,"q":1056,"a":1057},"array-from-vs-spread","When is Array.from better than spread?","`Array.from` accepts a **mapping function** and works on **array-like**\nobjects (those with `length` but no `Symbol.iterator`), which spread can't\nhandle.\n\n```js\nArray.from({ length: 3 }, (_, i) => i)  \u002F\u002F [0, 1, 2]  array-like + map\n[...{ length: 3 }]                       \u002F\u002F TypeError, not iterable\n```\n\nUse spread for iterables and brevity; use `Array.from` for array-likes or\nwhen you want to map during creation.\n",{"id":1059,"difficulty":63,"q":1060,"a":1061},"clone-and-modify","How do you immutably add or remove an item using spread?","Build a new array around the change instead of mutating.\n\n```js\nconst added   = [...arr, item]                 \u002F\u002F append\nconst prepend = [item, ...arr]                 \u002F\u002F prepend\nconst removed = [...arr.slice(0, i), ...arr.slice(i + 1)]  \u002F\u002F remove at i\n```\n\nThis is the standard pattern for React\u002FRedux state. The ES2023\n`arr.with(i, val)` and `toSpliced` cover replace\u002Fremove even more cleanly.\n",{"id":1063,"difficulty":63,"q":1064,"a":1065},"spread-order-matters","Does the order of spread elements matter?","Yes — elements land in source order, so later items can override or follow\nearlier ones.\n\n```js\n[...a, ...b]   \u002F\u002F a's items first, then b's\n[...b, ...a]   \u002F\u002F reversed grouping\n```\n\nUnlike object spread (where later keys win), array spread doesn't\n\"override\" — every element is kept; only the resulting positions differ.\n",{"id":1067,"difficulty":84,"q":1068,"a":1069},"nested-default-skip-combo","Can you combine skipping, defaults, and rest in one pattern?","Yes — they compose freely, as long as rest stays last.\n\n```js\nconst [, second = 0, ...rest] = [1]\nsecond  \u002F\u002F 0     (skipped first, defaulted missing second)\nrest    \u002F\u002F []    nothing left\n```\n\nPowerful but easy to over-pack; if a single pattern needs all three, it's\noften clearer to split into a couple of statements.\n",{"id":1071,"difficulty":71,"q":1072,"a":1073},"destructure-return-values","How is array destructuring used to return multiple values?","A function returns an array (or tuple-like) and the caller destructures it\npositionally — the pattern behind React's `useState`.\n\n```js\nfunction minMax(arr) {\n  return [Math.min(...arr), Math.max(...arr)]\n}\nconst [lo, hi] = minMax([3, 1, 9])   \u002F\u002F lo=1, hi=9\n```\n\nUse array returns when order is meaningful and stable; prefer an object\nreturn when callers should pick fields by name.\n",{"id":1075,"difficulty":71,"q":1076,"a":1077},"spread-set-dedupe","How do you dedupe an array with spread and a Set?","Wrap in a `Set` (drops duplicates by SameValueZero), then spread back to an\narray.\n\n```js\nconst unique = [...new Set([1, 1, 2, 3, 3])]  \u002F\u002F [1, 2, 3]\n```\n\nIt preserves first-seen order and is the idiomatic one-liner. Note it\ndedupes by reference for objects, so identical-looking objects won't\ncollapse.\n",{"id":1079,"difficulty":63,"q":1080,"a":1081},"flatten-with-spread","Can you flatten an array of arrays with spread?","For a known, small number of arrays, yes. For an arbitrary array of\narrays, prefer **`flat`** or `reduce`.\n\n```js\n[...a, ...b]                 \u002F\u002F fine for a fixed set\n[[1],[2],[3]].flat()         \u002F\u002F [1, 2, 3]  arbitrary length\nrows.reduce((acc, r) => [...acc, ...r], [])  \u002F\u002F works but O(n²)\n```\n\nThe `reduce`-with-spread version reallocates each step — use `flat()` or\n`acc.push(...r)` for performance.\n",{"id":1083,"difficulty":71,"q":1084,"a":1085},"spread-max-min","How do you find the max or min of an array?","Spread the array into `Math.max`\u002F`Math.min`.\n\n```js\nMath.max(...[3, 9, 1])  \u002F\u002F 9\nMath.min(...[3, 9, 1])  \u002F\u002F 1\n```\n\nCaveat: `Math.max()` of an **empty** array is `-Infinity` (and `min` is\n`Infinity`), and spreading a massive array may exceed argument limits — use\n`reduce` for those cases.\n",{"id":1087,"difficulty":71,"q":1088,"a":1089},"ignore-with-underscore","How do you conventionally ignore destructured values you don't need?","Either skip with an empty slot, or bind to a throwaway name like `_`.\n\n```js\nconst [, , third] = list       \u002F\u002F skip slots\nconst [_a, _b, third2] = list  \u002F\u002F name-but-ignore convention\n```\n\nThe underscore is just a normal variable (linters often allow an `_`\nprefix to mean \"unused\"). Skipping slots avoids creating bindings at all.\n",{"id":1091,"difficulty":84,"q":1092,"a":1093},"destructure-generator","What happens when you destructure a generator or infinite iterable?","Destructuring pulls only as many values as the pattern needs and then\nstops — so it works on **infinite** iterables.\n\n```js\nfunction* naturals() { let n = 1; while (true) yield n++ }\nconst [a, b, c] = naturals()\na, b, c   \u002F\u002F 1, 2, 3   only three pulled\n```\n\nBut a **rest element** (`const [first, ...rest]`) would try to drain the\nwhole iterable and hang forever — never use rest on an infinite source.\n",{"id":1095,"difficulty":84,"q":1096,"a":1097},"swap-without-temp-perf","Is destructuring swap as fast as a temp variable?","Functionally identical; performance is essentially the same in modern\nengines, though a destructuring swap allocates a small array literal that\nthe optimizer usually elides.\n\n```js\n[a, b] = [b, a]          \u002F\u002F readable, idiomatic\nconst t = a; a = b; b = t \u002F\u002F traditional, zero allocation\n```\n\nPrefer the destructuring form for clarity; only the traditional swap in\nextremely hot numeric loops where you've profiled an actual difference.\n",{"description":61},"JavaScript array destructuring and spread interview questions — defaults, skipping, swapping, nested patterns, rest elements, copying and merging arrays, spread vs concat and consuming iterables.","javascript\u002Farrays\u002Fdestructuring-spread","Array Destructuring & Spread","dwUK35g8bIJziTXcSu72Y0e_b_MJftZi1sERh1noiQ0",{"id":1104,"title":1105,"body":1106,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":1110,"navigation":66,"order":22,"path":1111,"questions":1112,"related":207,"seo":1237,"seoDescription":1238,"stem":1239,"subtopic":1240,"topic":962,"topicSlug":963,"updated":214,"__hash__":1241},"qa\u002Fjavascript\u002Farrays\u002Fmutating-vs-nonmutating.md","Mutating Vs Nonmutating",{"type":58,"value":1107,"toc":1108},[],{"title":61,"searchDepth":22,"depth":22,"links":1109},[],{},"\u002Fjavascript\u002Farrays\u002Fmutating-vs-nonmutating",[1113,1117,1121,1125,1129,1133,1137,1141,1145,1149,1153,1157,1161,1165,1169,1173,1177,1181,1185,1189,1193,1197,1201,1205,1209,1213,1217,1221,1225,1229,1233],{"id":1114,"difficulty":71,"q":1115,"a":1116},"what-is-mutation","What does it mean for an array method to mutate the array?","A **mutating** method changes the **original array in place** rather than\nreturning a fresh copy. The variable still points to the same array, but its\ncontents have changed.\n\n```js\nconst arr = [1, 2, 3]\narr.push(4) \u002F\u002F mutates: arr is now [1, 2, 3, 4]\n```\n\nThis matters because other code holding a reference to the same array sees the\nchange too — a frequent source of surprising bugs in shared state.\n",{"id":1118,"difficulty":63,"q":1119,"a":1120},"list-mutating","Which array methods mutate the original array?","The classic mutators all change the array in place:\n\n```text\npush, pop, shift, unshift  -> add\u002Fremove ends\nsplice                     -> insert\u002Fremove\u002Freplace anywhere\nsort, reverse              -> reorder\nfill, copyWithin           -> overwrite ranges\n```\n\nA memory aid: if a method changes **length or order**, it almost certainly\nmutates. The notable surprise is that **sort** and **reverse** mutate — many\nassume they return a new array like `map`.\n",{"id":1122,"difficulty":63,"q":1123,"a":1124},"list-nonmutating","Which common array methods return a new array instead of mutating?","These leave the original untouched and return a **new array**:\n\n```text\nmap, filter, slice, concat, flat, flatMap\ntoSorted, toReversed, toSpliced, with   (ES2023)\n```\n\nPlus the spread copy `[...arr]`. As a rule, the **iteration\u002Ftransform** methods\nare non-mutating, while the **in-place edit** methods mutate. Knowing which is\nwhich is essential for writing predictable code.\n",{"id":1126,"difficulty":71,"q":1127,"a":1128},"push-vs-concat","What is the difference between push and concat?","**push** mutates the array and returns the **new length**; **concat** returns a\n**new array** and leaves the original alone.\n\n```js\nconst a = [1, 2]\na.push(3)        \u002F\u002F a is [1,2,3], returns 3\nconst b = a.concat(4) \u002F\u002F b is [1,2,3,4], a unchanged\n```\n\nPitfall: people sometimes write `arr = arr.push(x)`, which sets `arr` to a\nnumber (the length). Use `concat` or spread when you want a new array\nreference.\n",{"id":1130,"difficulty":63,"q":1131,"a":1132},"slice-vs-splice","What is the difference between slice and splice?","**slice** is **non-mutating**: it returns a shallow copy of a range. **splice**\n**mutates**: it removes\u002Finserts elements in place and returns the removed ones.\n\n```js\nconst arr = [1, 2, 3, 4]\narr.slice(1, 3)     \u002F\u002F [2, 3], arr unchanged\narr.splice(1, 2)    \u002F\u002F removes [2, 3], arr is now [1, 4]\n```\n\nThe names look alike but behave oppositely on mutation. Confusing them is a\nclassic bug — remember **slice = copy, splice = surgery**.\n",{"id":1134,"difficulty":63,"q":1135,"a":1136},"sort-mutates","Does sort mutate the array?","Yes. **sort** sorts the array **in place** and also returns a reference to that\n**same** array — so both the original and the return value are sorted.\n\n```js\nconst arr = [3, 1, 2]\nconst sorted = arr.sort()\nsorted === arr \u002F\u002F true — same array\narr            \u002F\u002F [1, 2, 3] — original is changed\n```\n\nTo sort without mutating, copy first (`[...arr].sort()`) or use **toSorted()**\nin modern environments. The same applies to `reverse`.\n",{"id":1138,"difficulty":63,"q":1139,"a":1140},"tosorted","What is toSorted and how does it differ from sort?","**toSorted** (ES2023) returns a **new sorted array** and leaves the original\nunchanged — the immutable counterpart of `sort`.\n\n```js\nconst arr = [3, 1, 2]\nconst sorted = arr.toSorted() \u002F\u002F [1, 2, 3]\narr                           \u002F\u002F [3, 1, 2] — untouched\n```\n\nIt takes the same optional comparator as `sort`. Use it to avoid the classic\n`[...arr].sort()` copy dance, especially in React state where mutating is a\nbug.\n",{"id":1142,"difficulty":63,"q":1143,"a":1144},"toreversed-tospliced-with","What do toReversed, toSpliced, and with do?","They are the **immutable** versions of `reverse`, `splice`, and index\nassignment, all returning a **new array** (ES2023).\n\n```js\nconst arr = [1, 2, 3]\narr.toReversed()       \u002F\u002F [3, 2, 1], arr unchanged\narr.toSpliced(1, 1, 9) \u002F\u002F [1, 9, 3], arr unchanged\narr.with(0, 100)       \u002F\u002F [100, 2, 3], arr unchanged\n```\n\n`with(i, value)` is the immutable replacement for `arr[i] = value`. Together\nthese let you write update logic without copying first.\n",{"id":1146,"difficulty":84,"q":1147,"a":1148},"why-mutation-bugs","Why does mutation cause bugs in shared state?","When two variables reference the **same array**, mutating through one changes\nwhat the other sees. Functions that mutate their arguments cause **action at a\ndistance**.\n\n```js\nconst original = [1, 2, 3]\nconst sorted = original\nsorted.sort((a, b) => b - a)\noriginal \u002F\u002F [3, 2, 1] — caller's array got reordered\n```\n\nFrameworks like React rely on **referential equality** to detect changes;\nmutating in place keeps the same reference, so the UI may not re-render.\nReturning new arrays avoids both classes of bug.\n",{"id":1150,"difficulty":71,"q":1151,"a":1152},"copy-array-ways","What are the ways to copy an array?","For a **shallow** copy, any of these work:\n\n```js\nconst a = [1, 2, 3]\nconst b = [...a]        \u002F\u002F spread (most common)\nconst c = a.slice()     \u002F\u002F no args = full copy\nconst d = Array.from(a) \u002F\u002F\nconst e = a.concat()    \u002F\u002F\n```\n\nAll four copy the top level only. If the array holds objects, the copies share\nthose objects — see deep copying for nested data.\n",{"id":1154,"difficulty":63,"q":1155,"a":1156},"shallow-vs-deep","What is the difference between a shallow and a deep copy of an array?","A **shallow** copy duplicates the array but shares the **same nested object\nreferences**. A **deep** copy duplicates everything recursively.\n\n```js\nconst arr = [{ n: 1 }]\nconst shallow = [...arr]\nshallow[0].n = 99\narr[0].n \u002F\u002F 99 — nested object is shared\n\nconst deep = structuredClone(arr)\ndeep[0].n = 1\narr[0].n \u002F\u002F 99 — independent\n```\n\nSpread\u002Fslice are shallow; reach for `structuredClone` when nested data must be\nindependent.\n",{"id":1158,"difficulty":63,"q":1159,"a":1160},"structuredclone","When and how do you use structuredClone for arrays?","**structuredClone** does a true **deep copy** of arrays containing nested\nobjects, arrays, Maps, Sets, Dates, and more — without the limitations of\nJSON tricks.\n\n```js\nconst data = [{ id: 1, tags: ['a'] }]\nconst copy = structuredClone(data) \u002F\u002F fully independent\n```\n\nCaveat: it **cannot clone functions, DOM nodes, or class instances** with\nmethods (it throws or drops the prototype). It's built into modern Node and all\ncurrent browsers.\n",{"id":1162,"difficulty":63,"q":1163,"a":1164},"json-deep-copy","What are the pitfalls of JSON.parse(JSON.stringify(arr)) for deep copy?","It deep-copies plain data but **silently corrupts** anything non-JSON:\n\n```js\nconst arr = [{ d: new Date(), fn: () => {}, u: undefined, n: NaN }]\nJSON.parse(JSON.stringify(arr))\n\u002F\u002F Date -> string, fn -> dropped, undefined -> dropped, NaN -> null\n```\n\nIt also throws on **circular references**. Prefer `structuredClone` for deep\ncopies; reserve the JSON trick for arrays of plain, JSON-safe values where the\nconversions don't matter.\n",{"id":1166,"difficulty":63,"q":1167,"a":1168},"immutable-add","How do you add an item to an array immutably?","Build a **new array** with spread instead of `push`\u002F`unshift`:\n\n```js\nconst arr = [1, 2, 3]\nconst appended = [...arr, 4]   \u002F\u002F add to end\nconst prepended = [0, ...arr]  \u002F\u002F add to start\narr \u002F\u002F [1, 2, 3] — unchanged\n```\n\nThis pattern is standard in Redux reducers and React `setState`, where mutating\nthe existing array would break change detection and time-travel debugging.\n",{"id":1170,"difficulty":63,"q":1171,"a":1172},"immutable-remove","How do you remove an item from an array immutably?","Use **filter** (by value\u002Fpredicate) or **slice + spread** (by index) to produce\na new array.\n\n```js\nconst arr = [1, 2, 3, 4]\narr.filter(n => n !== 3)             \u002F\u002F [1, 2, 4] by value\nconst i = 2\n[...arr.slice(0, i), ...arr.slice(i + 1)] \u002F\u002F [1, 2, 4] by index\narr.toSpliced(i, 1)                  \u002F\u002F [1, 2, 4] ES2023\n```\n\nAvoid `splice`, which mutates. `toSpliced` is the cleanest modern option for\nindex-based removal.\n",{"id":1174,"difficulty":63,"q":1175,"a":1176},"immutable-update","How do you update an item at an index immutably?","Use **map** with the index, or **with()** in modern environments — never\n`arr[i] = x`, which mutates.\n\n```js\nconst arr = [1, 2, 3]\narr.map((v, idx) => (idx === 1 ? 99 : v)) \u002F\u002F [1, 99, 3]\narr.with(1, 99)                            \u002F\u002F [1, 99, 3] ES2023\narr \u002F\u002F [1, 2, 3] — unchanged\n```\n\nFor arrays of objects, also spread the object: `arr.map(o => o.id === id ? {\n...o, done: true } : o)` to avoid mutating the nested object.\n",{"id":1178,"difficulty":84,"q":1179,"a":1180},"freeze-array","Does Object.freeze make an array fully immutable?","It makes it **shallowly** immutable: you can't add, remove, or reassign\ntop-level elements, but **nested objects stay mutable**.\n\n```js\nconst arr = Object.freeze([{ n: 1 }])\narr.push(2)   \u002F\u002F throws in strict mode (or silently fails)\narr[0].n = 99 \u002F\u002F still works — nested object not frozen\n```\n\nFor deep immutability you must freeze recursively (a \"deep freeze\"). Also note\nmutating methods like `push` throw on a frozen array in strict mode.\n",{"id":1182,"difficulty":63,"q":1183,"a":1184},"fill","What does fill do and does it mutate?","**fill** overwrites a range of the array with a static value **in place** — it\nmutates and returns the same array.\n\n```js\nconst arr = [1, 2, 3, 4]\narr.fill(0, 1, 3) \u002F\u002F [1, 0, 0, 4], arr mutated\nnew Array(3).fill(0) \u002F\u002F [0, 0, 0] — common init pattern\n```\n\nGotcha: filling with a **shared object** puts the **same reference** in every\nslot: `new Array(3).fill([])` gives three references to one array. Use\n`Array.from({length:3}, () => [])` for distinct objects.\n",{"id":1186,"difficulty":84,"q":1187,"a":1188},"copywithin","What does copyWithin do?","**copyWithin(target, start, end)** copies a slice of the array to another\nposition **within the same array**, in place, without changing its length.\n\n```js\nconst arr = [1, 2, 3, 4, 5]\narr.copyWithin(0, 3) \u002F\u002F [4, 5, 3, 4, 5] — copy from index 3 to 0\n```\n\nIt mutates and is rarely used in app code — it exists mainly for high\nperformance buffer manipulation. Worth recognizing in interviews but seldom\nreached for in practice.\n",{"id":1190,"difficulty":71,"q":1191,"a":1192},"reverse-mutates","Does reverse mutate the array?","Yes — **reverse** reverses the array **in place** and returns a reference to the\nsame array.\n\n```js\nconst arr = [1, 2, 3]\narr.reverse()\narr \u002F\u002F [3, 2, 1] — original changed\n```\n\nTo reverse without mutating, use `[...arr].reverse()` or **toReversed()**. This\nmutation surprises people who expect array methods to be functional like `map`.\n",{"id":1194,"difficulty":71,"q":1195,"a":1196},"assignment-not-copy","Why doesn't const b = a create a copy of the array?","Arrays are **reference types**. Assignment copies the **reference**, not the\ndata, so both names point at the **same array**.\n\n```js\nconst a = [1, 2, 3]\nconst b = a\nb.push(4)\na \u002F\u002F [1, 2, 3, 4] — same array\n```\n\nTo get an independent array you must explicitly copy: `const b = [...a]`. This\nreference behavior underlies most accidental-mutation bugs.\n",{"id":1198,"difficulty":63,"q":1199,"a":1200},"mutation-in-functions","How can passing an array to a function mutate the caller's array?","The function receives the **same reference**, so any mutating method affects the\ncaller's array.\n\n```js\nfunction addItem(arr) { arr.push('x') } \u002F\u002F mutates caller\nconst list = [1]\naddItem(list)\nlist \u002F\u002F [1, 'x']\n```\n\nWrite **pure** functions that return new arrays instead: `function addItem(arr)\n{ return [...arr, 'x'] }`. This keeps call sites free of surprises and makes the\ncode easier to test.\n",{"id":1202,"difficulty":63,"q":1203,"a":1204},"spread-shallow","Is the spread operator a deep or shallow copy for arrays?","**Shallow.** Spread copies the top-level elements; nested objects\u002Farrays are\nstill **shared by reference**.\n\n```js\nconst arr = [[1], [2]]\nconst copy = [...arr]\ncopy[0].push(99)\narr[0] \u002F\u002F [1, 99] — inner array shared\n```\n\nFor nested data you need a deep copy (`structuredClone`) or to spread each\nlevel. Treat spread as a fast top-level clone, nothing more.\n",{"id":1206,"difficulty":84,"q":1207,"a":1208},"react-mutation","Why must you avoid mutating arrays in React state?","React decides whether to re-render by comparing the **previous and next\nreference**. Mutating in place keeps the **same reference**, so React thinks\nnothing changed.\n\n```js\n\u002F\u002F mutation — same reference, no re-render\nitems.push(newItem); setItems(items)\n\u002F\u002F new reference — triggers re-render\nsetItems([...items, newItem])\n```\n\nAlways create a new array (`map`, `filter`, spread, `toSorted`, `with`) when\nupdating state so React sees the change.\n",{"id":1210,"difficulty":63,"q":1211,"a":1212},"empty-array-length","How does setting arr.length mutate the array?","Assigning to **length** mutates in place: shrinking truncates elements,\ngrowing pads with empty slots, and `length = 0` empties the array.\n\n```js\nconst arr = [1, 2, 3, 4]\narr.length = 2 \u002F\u002F [1, 2] — truncated\narr.length = 0 \u002F\u002F [] — cleared\n```\n\n`arr.length = 0` is a fast in-place clear that affects every reference to the\narray. To clear without mutating shared references, reassign: `arr = []`.\n",{"id":1214,"difficulty":71,"q":1215,"a":1216},"pop-shift-return","What do pop and shift return, and do they mutate?","Both **mutate** and return the **removed element**. `pop` removes from the end,\n`shift` from the start.\n\n```js\nconst arr = [1, 2, 3]\narr.pop()   \u002F\u002F returns 3, arr is [1, 2]\narr.shift() \u002F\u002F returns 1, arr is [2]\n```\n\nNote `shift`\u002F`unshift` are **O(n)** because every remaining element must be\nreindexed, whereas `push`\u002F`pop` are O(1). Prefer end operations in hot loops.\n",{"id":1218,"difficulty":71,"q":1219,"a":1220},"concat-vs-spread","Are concat and spread interchangeable for combining arrays?","Mostly yes — both return a **new array** without mutating. Spread reads more\nnaturally; `concat` has one nicety: it accepts **non-array values** directly.\n\n```js\n[...a, ...b]      \u002F\u002F merge two arrays\na.concat(b)       \u002F\u002F same result\na.concat(b, 5, 6) \u002F\u002F concat flattens array args and appends values\n[...a, b]         \u002F\u002F pushes the array b as a single element\n```\n\nFor huge arrays `concat` can be marginally faster, but readability usually\nfavors spread.\n",{"id":1222,"difficulty":84,"q":1223,"a":1224},"in-place-dedupe","How do you dedupe an array, mutating versus non-mutating?","The clean, **non-mutating** way uses a `Set`:\n\n```js\nconst unique = [...new Set(arr)] \u002F\u002F new array, order preserved\n```\n\nAn in-place dedupe is fiddly and error-prone (you'd `splice` while iterating,\nwhich shifts indices). Prefer the Set approach. Note it uses **SameValueZero**,\nso `NaN` is deduped correctly but distinct objects with equal contents are not.\n",{"id":1226,"difficulty":63,"q":1227,"a":1228},"immutability-libraries","What problem do libraries like Immer solve for arrays?","They let you write **mutating-looking** code that actually produces a **new,\nimmutable** array under the hood, avoiding verbose spread chains for deeply\nnested updates.\n\n```js\nconst next = produce(state, draft => {\n  draft.items.push(newItem) \u002F\u002F looks like mutation\n}) \u002F\u002F state is untouched, next is a new tree\n```\n\nImmer tracks changes to a proxy \"draft\" and builds the new structure for you.\nIt's popular in Redux Toolkit precisely because deep immutable updates with\nspread get unwieldy.\n",{"id":1230,"difficulty":84,"q":1231,"a":1232},"detect-mutation","How can you guard against accidental mutation during development?","Use **Object.freeze** in development to make accidental mutation throw, lean on\n**const** (which prevents reassignment, not mutation), and adopt lint rules or\nlibraries that enforce immutability.\n\n```js\nconst config = Object.freeze([1, 2, 3])\nconfig.push(4) \u002F\u002F throws in strict mode — caught early\n```\n\nIn TypeScript, `readonly` arrays and `as const` give **compile-time**\nprotection with zero runtime cost, catching mutation before it ships.\n",{"id":1234,"difficulty":63,"q":1235,"a":1236},"prefer-immutable","When should you prefer immutable updates over mutation?","Prefer **immutable** updates whenever the array is **shared** — across\ncomponents, stored in framework state, or passed between modules — because new\nreferences make change tracking and reasoning reliable.\n\n```js\n\u002F\u002F shared state -> immutable\nsetItems(items.filter(i => i.id !== id)) \u002F\u002F\n```\n\n**Mutation is fine** for short-lived local arrays you fully own inside a\nfunction, where in-place edits are faster and no one else can observe them.\n",{"description":61},"JavaScript array mutation interview questions — which methods mutate versus return a new array, immutability patterns, copying arrays, the new toSorted and with methods, and structuredClone for nested data.","javascript\u002Farrays\u002Fmutating-vs-nonmutating","Mutating vs Non-Mutating","54QuTuRi8ysB-Ri5IyNJ6VfxTJXeWyfqI2yjBC5sMQg",{"id":1243,"title":1244,"body":1245,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":1249,"navigation":66,"order":31,"path":1250,"questions":1251,"related":207,"seo":1372,"seoDescription":1373,"stem":1374,"subtopic":1375,"topic":962,"topicSlug":963,"updated":214,"__hash__":1376},"qa\u002Fjavascript\u002Farrays\u002Fsearching-sorting.md","Searching Sorting",{"type":58,"value":1246,"toc":1247},[],{"title":61,"searchDepth":22,"depth":22,"links":1248},[],{},"\u002Fjavascript\u002Farrays\u002Fsearching-sorting",[1252,1256,1260,1264,1268,1272,1276,1278,1282,1286,1290,1293,1297,1301,1305,1309,1313,1316,1320,1324,1328,1332,1336,1340,1344,1348,1352,1356,1360,1364,1368],{"id":1253,"difficulty":71,"q":1254,"a":1255},"indexof-basics","How does indexOf work and what does it return when nothing is found?","**`indexOf`** returns the index of the first element strictly equal\n(`===`) to the search value, or **`-1`** if it is not present.\n\n```js\nconst a = ['x', 'y', 'z']\na.indexOf('y')   \u002F\u002F 1\na.indexOf('q')   \u002F\u002F -1  the \"not found\" sentinel\n```\n\nThe classic pitfall is treating `-1` as falsy: `if (a.indexOf(x))` is\n**wrong** because index `0` is also falsy. Compare explicitly with\n`!== -1`, or prefer `includes` when you only need a boolean.\n",{"id":1257,"difficulty":71,"q":1258,"a":1259},"lastindexof","What is the difference between indexOf and lastIndexOf?","**`indexOf`** searches front-to-back and returns the first match;\n**`lastIndexOf`** searches back-to-front and returns the last match.\nBoth use `===` and return `-1` when absent.\n\n```js\nconst a = [1, 2, 3, 2, 1]\na.indexOf(2)      \u002F\u002F 1\na.lastIndexOf(2)  \u002F\u002F 3  last occurrence\n```\n\nEach also takes an optional start index. A subtle point: for\n`lastIndexOf` the second argument is where to *begin searching\nbackwards*, so `a.lastIndexOf(2, 2)` searches indices 2->0.\n",{"id":1261,"difficulty":63,"q":1262,"a":1263},"includes-vs-indexof","When should you use includes instead of indexOf?","Use **`includes`** when you only care *whether* a value exists — it\nreturns a boolean and reads clearly. Use **`indexOf`** when you need the\n*position*.\n\n```js\nif (tags.includes('urgent')) { \u002F* ... *\u002F }   \u002F\u002F clear intent\nconst at = tags.indexOf('urgent')            \u002F\u002F when you need where\n```\n\nThe other reason to prefer `includes`: it finds `NaN`, which `indexOf`\ncannot (see the next question).\n",{"id":1265,"difficulty":63,"q":1266,"a":1267},"nan-search-gotcha","Why can't indexOf find NaN, but includes can?","`indexOf` compares with `===`, and `NaN === NaN` is **false** — so it can\nnever match. `includes` uses the **SameValueZero** algorithm, which\ntreats `NaN` as equal to `NaN`.\n\n```js\n[NaN].indexOf(NaN)    \u002F\u002F -1  can't find it\n[NaN].includes(NaN)   \u002F\u002F true\n```\n\nSameValueZero is also why `includes(0)` matches both `+0` and `-0`. If\nyou must locate a `NaN` index, use `findIndex(Number.isNaN)`.\n",{"id":1269,"difficulty":71,"q":1270,"a":1271},"find-vs-filter","What is the difference between find and filter?","**`find`** returns the **first element** that satisfies the predicate (or\n`undefined`); **`filter`** returns a **new array** of *all* matches.\n\n```js\nusers.find(u => u.id === 7)     \u002F\u002F the one user, or undefined\nusers.filter(u => u.active)     \u002F\u002F array of every active user\n```\n\nUse `find` for \"give me the one I want\" — it also short-circuits on the\nfirst match, so it's cheaper than `filter()[0]` which scans the whole\narray.\n",{"id":1273,"difficulty":71,"q":1274,"a":1275},"findindex","When would you use findIndex over indexOf?","**`indexOf`** searches by value equality; **`findIndex`** searches by a\n**predicate function**, so it works for objects and complex conditions.\n\n```js\nconst i = users.indexOf(someUser)          \u002F\u002F needs the exact reference\nconst j = users.findIndex(u => u.id === 7) \u002F\u002F search by a property\n```\n\nBoth return `-1` when nothing matches. Reach for `findIndex` whenever the\nmatch is \"the element where some condition holds\" rather than \"this exact\nvalue.\"\n",{"id":864,"difficulty":63,"q":865,"a":1277},"They are the back-to-front counterparts of `find`\u002F`findIndex`: they walk\nthe array **from the end** and return the first matching element \u002F index.\n\n```js\nconst nums = [1, 8, 3, 9, 2]\nnums.findLast(n => n > 4)       \u002F\u002F 9  last match, not first\nnums.findLastIndex(n => n > 4)  \u002F\u002F 3\n```\n\nBefore these (ES2023) you'd reverse a copy or loop manually. They're handy\nfor \"most recent\" lookups in append-ordered data like logs.\n",{"id":1279,"difficulty":71,"q":1280,"a":1281},"some-every-search","How do some and every help with searching?","**`some`** answers \"does *any* element match?\" and **`every`** answers\n\"do *all* elements match?\" — both return a boolean and short-circuit.\n\n```js\nnums.some(n => n \u003C 0)    \u002F\u002F true if there's at least one negative\nnums.every(n => n > 0)   \u002F\u002F true only if all are positive\n```\n\n`some` stops at the first `true`; `every` stops at the first `false`. A\ngotcha: `every` on an **empty array is `true`** (vacuous truth) and `some`\non an empty array is `false`.\n",{"id":1283,"difficulty":63,"q":1284,"a":1285},"sort-default-gotcha","Why does sorting numbers with sort() give wrong results?","Without a comparator, **`sort` converts elements to strings** and compares\nthem by UTF-16 code unit — so numbers sort lexicographically.\n\n```js\n[10, 1, 2, 20].sort()            \u002F\u002F [1, 10, 2, 20]  \"10\" \u003C \"2\"\n[10, 1, 2, 20].sort((a,b)=>a-b)  \u002F\u002F [1, 2, 10, 20]\n```\n\nAlways pass a comparator for numbers. This string-coercion default trips\nup nearly everyone at least once.\n",{"id":1287,"difficulty":71,"q":1288,"a":1289},"numeric-comparator","How do you write an ascending and descending numeric comparator?","A comparator returns a **negative** number if `a` should come first, a\n**positive** number if `b` should, and `0` to leave order unchanged.\n\n```js\narr.sort((a, b) => a - b)   \u002F\u002F ascending\narr.sort((a, b) => b - a)   \u002F\u002F descending\n```\n\nThe `a - b` trick works only for numbers. Don't return a boolean\n(`a > b`) — coerced to `0`\u002F`1` it never yields a negative, so the sort is\nbroken.\n",{"id":1134,"difficulty":63,"q":1291,"a":1292},"Does sort() mutate the array? How do you sort without mutating?","Yes — **`sort` sorts in place and returns the same array reference**.\nThat can surprise callers sharing the array.\n\n```js\nconst a = [3, 1, 2]\nconst b = a.sort((x,y)=>x-y)\nb === a            \u002F\u002F true  original mutated\n\nconst sorted = [...a].sort((x,y)=>x-y)  \u002F\u002F copy first\nconst safe = a.toSorted((x,y)=>x-y)     \u002F\u002F ES2023, returns new array\n```\n\nPrefer `toSorted` (or spread-then-sort) in code that values immutability,\ne.g. React state.\n",{"id":1294,"difficulty":84,"q":1295,"a":1296},"stable-sort","Is JavaScript's sort stable, and why does that matter?","Since ES2019 `sort` is guaranteed **stable**: elements the comparator\ntreats as equal keep their original relative order. This makes\n**multi-pass sorting** reliable.\n\n```js\n\u002F\u002F sort by name, then by age — age becomes the primary key,\n\u002F\u002F ties broken by the earlier name order\npeople.sort((a,b)=>a.name.localeCompare(b.name))\n      .sort((a,b)=>a.age - b.age)  \u002F\u002F stable keeps name order within an age\n```\n\nBefore ES2019, engines like V8 used an unstable sort for large arrays, so\nthis pattern wasn't portable.\n",{"id":1298,"difficulty":63,"q":1299,"a":1300},"sort-objects","How do you sort an array of objects by a property?","Compare the property inside the comparator. Subtract for numbers, use\n`localeCompare` for strings.\n\n```js\nusers.sort((a, b) => a.age - b.age)              \u002F\u002F numeric field\nusers.sort((a, b) => a.name.localeCompare(b.name)) \u002F\u002F string field\n```\n\nDon't use `a.name > b.name` directly — it returns a boolean and breaks the\ncomparator contract. Remember it mutates, so copy first if needed.\n",{"id":1302,"difficulty":84,"q":1303,"a":1304},"multi-key-sort","How do you sort by multiple keys?","Evaluate keys in priority order and return the first non-zero comparison.\n\n```js\npeople.sort((a, b) =>\n  a.lastName.localeCompare(b.lastName) ||  \u002F\u002F primary\n  a.firstName.localeCompare(b.firstName) || \u002F\u002F tiebreaker\n  a.age - b.age                             \u002F\u002F final tiebreaker\n)\n```\n\nThe `||` chain works because a `0` (equal) is falsy, so it falls through\nto the next key. Clean and avoids nested `if`s.\n",{"id":1306,"difficulty":63,"q":1307,"a":1308},"localecompare","Why use localeCompare for sorting strings?","Comparing strings with `\u003C`\u002F`>` uses raw UTF-16 code units, which mishandles\naccents and locale rules. **`localeCompare`** sorts the way humans expect\nfor a given language.\n\n```js\n['é', 'a', 'z'].sort()                       \u002F\u002F ['a', 'z', 'é']\n['é', 'a', 'z'].sort((a,b)=>a.localeCompare(b)) \u002F\u002F ['a', 'é', 'z']\n```\n\nFor large arrays, build a reusable `Intl.Collator` and pass its `compare`\nmethod — it's much faster than calling `localeCompare` repeatedly.\n",{"id":1310,"difficulty":63,"q":1311,"a":1312},"case-insensitive-sort","How do you sort strings case-insensitively?","Either lowercase both sides, or use `localeCompare` with the\n`sensitivity: 'base'` option (which also ignores accents).\n\n```js\narr.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))\n\u002F\u002F or\narr.sort((a, b) =>\n  a.localeCompare(b, undefined, { sensitivity: 'base' }))  \u002F\u002F\n```\n\nThe `Intl` option is preferable: lowercasing can be wrong for some\nlanguages (e.g. Turkish dotless İ).\n",{"id":1190,"difficulty":71,"q":1314,"a":1315},"Does reverse() mutate, and what's the immutable alternative?","Yes — **`reverse` reverses in place** and returns the same array. The\nES2023 immutable version is **`toReversed`**.\n\n```js\nconst a = [1, 2, 3]\na.reverse()        \u002F\u002F a is now [3, 2, 1]  mutated\nconst b = a.toReversed()  \u002F\u002F new array, a untouched\n```\n\nTo reverse-sort numbers, you don't need `reverse` at all — just flip the\ncomparator: `sort((x,y)=>y-x)`.\n",{"id":1317,"difficulty":63,"q":1318,"a":1319},"indexof-fromindex","How does the second argument to indexOf and includes work?","It's the **start index**. Searching begins there and continues to the end.\nNegative values count from the end.\n\n```js\nconst a = ['a', 'b', 'a', 'b']\na.indexOf('a', 1)    \u002F\u002F 2  (skips index 0)\na.includes('a', -1)  \u002F\u002F false (only looks at last element)\n```\n\nUseful for finding *all* occurrences in a loop: keep calling\n`indexOf(x, lastFound + 1)` until it returns `-1`.\n",{"id":1321,"difficulty":84,"q":1322,"a":1323},"find-all-indices","How do you find all indices where a condition holds?","There's no built-in, but `reduce` collects them in one pass, or `map` +\n`filter`.\n\n```js\nconst evens = nums.reduce((acc, n, i) => {\n  if (n % 2 === 0) acc.push(i)\n  return acc\n}, [])  \u002F\u002F array of indices\n```\n\nAvoid the naive `nums.map((n,i)=> n%2===0 ? i : -1).filter(i=>i!==-1)` —\nit's two passes and the `-1` sentinel is fragile if `0` is a valid index.\n",{"id":1325,"difficulty":84,"q":1326,"a":1327},"binary-search","When is a manual binary search worthwhile over includes\u002FindexOf?","`includes`\u002F`indexOf` are **O(n)** linear scans. If the array is **already\nsorted** and you search it many times, a **binary search** is O(log n).\n\n```js\nfunction bsearch(arr, target) {\n  let lo = 0, hi = arr.length - 1\n  while (lo \u003C= hi) {\n    const mid = (lo + hi) >> 1\n    if (arr[mid] === target) return mid\n    arr[mid] \u003C target ? (lo = mid + 1) : (hi = mid - 1)\n  }\n  return -1\n}\n```\n\nThe pitfall: the array **must** stay sorted, and `(lo+hi)>>1` assumes\nindices small enough to avoid overflow (fine in practice for arrays).\n",{"id":1329,"difficulty":84,"q":1330,"a":1331},"sort-numbers-strings-mix","What happens if you sort an array with mixed types?","The default sort stringifies everything, giving surprising order; a numeric\ncomparator on mixed types produces `NaN` comparisons that leave order\neffectively undefined.\n\n```js\n[3, '1', 2].sort()              \u002F\u002F ['1', 2, 3] — all compared as strings\n[3, 'x', 2].sort((a,b)=>a-b)    \u002F\u002F 'x'-num is NaN, order unreliable\n```\n\nNormalize types before sorting (e.g. `Number(x)`), or filter out invalid\nentries first. Mixed-type arrays are usually a data-modeling smell.\n",{"id":1333,"difficulty":84,"q":1334,"a":1335},"sort-undefined","How does sort handle undefined and holes?","`sort` moves all **`undefined`** values to the **end** without calling the\ncomparator on them, and **holes** in sparse arrays go after even those.\n\n```js\n[3, undefined, 1].sort((a,b)=>a-b)  \u002F\u002F [1, 3, undefined]\n```\n\nSo you can't reliably place `undefined` via a comparator — the engine\nhandles them specially. Strip or default them beforehand if you need\nspecific placement.\n",{"id":1337,"difficulty":63,"q":1338,"a":1339},"includes-object-reference","Why does includes return false for an object that \"looks\" the same?","`includes` uses identity (SameValueZero), so two distinct objects with the\nsame contents are **not** equal.\n\n```js\nconst arr = [{ id: 1 }]\narr.includes({ id: 1 })           \u002F\u002F false different reference\narr.some(o => o.id === 1)         \u002F\u002F true  compare by value\n```\n\nFor \"contains an object like this,\" use `some`\u002F`find` with a predicate, not\n`includes`\u002F`indexOf`.\n",{"id":1341,"difficulty":63,"q":1342,"a":1343},"tosorted-toreversed","What are toSorted, toReversed, toSpliced, and with?","They are ES2023 **non-mutating** versions of `sort`, `reverse`, `splice`,\nand bracket assignment — each returns a **new array**.\n\n```js\na.toSorted((x,y)=>x-y)   \u002F\u002F sorted copy\na.toReversed()           \u002F\u002F reversed copy\na.toSpliced(1, 2)        \u002F\u002F copy with items removed\u002Finserted\na.with(0, 'new')         \u002F\u002F copy with index 0 replaced\n```\n\nThey make immutable updates concise — especially `with`, which replaces the\nold `[...a.slice(0,i), val, ...a.slice(i+1)]` dance.\n",{"id":1345,"difficulty":63,"q":1346,"a":1347},"search-performance","When should you use a Set or Map instead of array searching?","Repeated `includes`\u002F`indexOf` lookups are **O(n)** each — O(n·m) overall.\nA **`Set`** gives O(1) membership tests.\n\n```js\nconst seen = new Set(bigArray)\nqueries.filter(q => seen.has(q))   \u002F\u002F O(1) per lookup\n```\n\nRule of thumb: if you search the same collection more than a handful of\ntimes, build a `Set`\u002F`Map` index once and query that instead.\n",{"id":1349,"difficulty":63,"q":1350,"a":1351},"dedupe-sorted","How do you remove duplicates, optionally keeping order?","A **`Set`** dedupes and preserves first-seen insertion order in one line.\n\n```js\nconst unique = [...new Set(arr)]   \u002F\u002F order preserved\n```\n\nFor objects (reference equality won't help), dedupe by a key with a `Map`:\n\n```js\nconst byId = [...new Map(users.map(u => [u.id, u])).values()]\n```\n",{"id":1353,"difficulty":84,"q":1354,"a":1355},"sort-comparator-cost","Why can repeated work inside a comparator be a performance problem?","The comparator runs **O(n log n)** times, so any expensive computation\ninside it is repeated constantly. Precompute keys once with a\n**Schwartzian transform**.\n\n```js\nconst sorted = items\n  .map(x => ({ x, key: expensiveKey(x) }))  \u002F\u002F compute once\n  .sort((a, b) => a.key - b.key)\n  .map(o => o.x)                              \u002F\u002F unwrap\n```\n\nThis trades a little memory for far fewer key computations than calling\n`expensiveKey` inside `sort`.\n",{"id":1357,"difficulty":71,"q":1358,"a":1359},"find-default","What does find return when nothing matches, and why be careful?","It returns **`undefined`**. Destructuring or accessing properties on the\nresult without a guard then throws.\n\n```js\nconst u = users.find(u => u.id === 99)\nu.name              \u002F\u002F TypeError if not found\nu?.name             \u002F\u002F optional chaining\nconst { name } = u ?? {}  \u002F\u002F safe default\n```\n\nAlways treat `find`'s result as possibly `undefined`.\n",{"id":1361,"difficulty":71,"q":1362,"a":1363},"indexof-vs-search-string","Does array indexOf relate to string indexOf?","They share a name and a `-1`-on-miss convention, but operate on different\nthings. **Array** `indexOf` matches an element by `===`; **string**\n`indexOf` finds a **substring**.\n\n```js\n['ab', 'cd'].indexOf('b')   \u002F\u002F -1  (no element equals 'b')\n'abcd'.indexOf('b')         \u002F\u002F 1   (substring position)\n```\n\nDon't expect array `indexOf` to do partial\u002Fsubstring matching — use\n`some(s => s.includes('b'))` for that.\n",{"id":1365,"difficulty":84,"q":1366,"a":1367},"sort-locale-numeric","How do you sort strings that contain numbers \"naturally\" (file2 \u003C file10)?","Default and `localeCompare` without options give `file10 \u003C file2`\n(lexicographic). Pass `{ numeric: true }` for **natural sort**.\n\n```js\n['file10','file2'].sort()  \u002F\u002F ['file10','file2']\n['file10','file2'].sort((a,b)=>\n  a.localeCompare(b, undefined, { numeric: true }))\n\u002F\u002F ['file2','file10']\n```\n\nCombine with `sensitivity: 'base'` for case\u002Faccent-insensitive natural\nordering of filenames and version strings.\n",{"id":1369,"difficulty":71,"q":1370,"a":1371},"empty-array-search","What do searching methods return on an empty array?","Consistent, safe defaults: `indexOf`\u002F`findIndex` return `-1`,\n`find` returns `undefined`, `includes`\u002F`some` return `false`, and\n`every` returns `true`.\n\n```js\n[].indexOf('x')   \u002F\u002F -1\n[].find(Boolean)  \u002F\u002F undefined\n[].some(Boolean)  \u002F\u002F false\n[].every(Boolean) \u002F\u002F true   vacuously\n```\n\nThe `every === true` on empty is the one that surprises people in\nvalidation logic — guard for emptiness if \"all valid\" shouldn't pass on no\ndata.\n",{"description":61},"JavaScript array searching and sorting interview questions — indexOf, includes, find, the sort() coercion gotcha, numeric comparators, stable sort, toSorted and sorting objects.","javascript\u002Farrays\u002Fsearching-sorting","Searching & Sorting","rwKZ3UXQprDpLSR117P9VFRLTkhBfPapY8I3dIMex0Q",{"id":1378,"title":1379,"body":1380,"description":61,"difficulty":84,"extension":64,"framework":11,"frameworkSlug":9,"meta":1384,"navigation":66,"order":22,"path":1385,"questions":1386,"related":207,"seo":1519,"seoDescription":1520,"stem":1521,"subtopic":1522,"topic":1523,"topicSlug":1524,"updated":1525,"__hash__":1526},"qa\u002Fjavascript\u002Fasync\u002Fevent-loop.md","Event Loop",{"type":58,"value":1381,"toc":1382},[],{"title":61,"searchDepth":22,"depth":22,"links":1383},[],{},"\u002Fjavascript\u002Fasync\u002Fevent-loop",[1387,1391,1395,1399,1403,1407,1411,1415,1419,1423,1427,1431,1435,1439,1443,1447,1451,1455,1459,1463,1467,1471,1475,1479,1483,1487,1491,1495,1499,1503,1507,1511,1515],{"id":1388,"difficulty":63,"q":1389,"a":1390},"what-is-event-loop","What is the event loop?","JavaScript runs on a **single thread** — one call stack, one thing at a time.\nThe event loop is the coordinator that lets that single thread *appear*\nconcurrent: it repeatedly checks \"is the call stack empty?\" and, when it is,\npulls the next queued callback and pushes it onto the stack to run.\n\nThe pieces involved:\n\n- **Call stack** — the function currently executing.\n- **Web\u002FNode APIs** — timers, network, I\u002FO that run *outside* the engine and\n  hand a callback back when done.\n- **Task & microtask queues** — where those finished callbacks wait.\n\n```js\nwhile (true) {\n  runUntilStackEmpty()   \u002F\u002F execute current synchronous work\n  drainMicrotasks()      \u002F\u002F then ALL queued microtasks\n  if (oneMacrotask) run(oneMacrotask) \u002F\u002F then exactly one macrotask, repeat\n}\n```\n\nSo async code never \"interrupts\" running code — it waits until the stack is\nclear, which is why the event loop is the heart of every \"what's the output\norder?\" interview question.\n",{"id":1392,"difficulty":71,"q":1393,"a":1394},"call-stack","What is the call stack?","The call stack is a **LIFO (last-in, first-out)** structure that tracks where\nthe program is in its execution. Calling a function **pushes** a frame (its\nlocal variables and return address); returning **pops** it. JavaScript has\nexactly one call stack, so it executes one frame at a time.\n\n```js\nfunction a() { b() }\nfunction b() { c() }\nfunction c() { throw new Error('boom') }\na()\n\u002F\u002F Stack at the throw (top first): c -> b -> a -> (global)\n\u002F\u002F That ordering is literally what a stack trace prints.\n```\n\nTwo consequences worth naming in an interview: deep\u002Finfinite recursion\noverflows the stack (`Maximum call stack size exceeded`), and because there's\nonly one stack, any long synchronous function **blocks** everything else until\nit returns.\n",{"id":1396,"difficulty":84,"q":1397,"a":1398},"macro-micro","What is the difference between the macrotask and microtask queues?","There are two priority levels of queued work, and the event loop treats them\nvery differently:\n\n- **Macrotasks** (a.k.a. \"tasks\"): `setTimeout`, `setInterval`,\n  `setImmediate`, I\u002FO callbacks, UI events. The loop runs **one** per\n  iteration.\n- **Microtasks**: promise `.then`\u002F`catch`\u002F`finally` callbacks,\n  `queueMicrotask`, `await` continuations, `MutationObserver`.\n\nThe critical rule: after each macrotask (and after the initial synchronous\nscript), the engine **drains the entire microtask queue** — including any\nmicrotasks those microtasks schedule — *before* picking up the next macrotask\nor rendering.\n\n```js\nsetTimeout(() => console.log('macro'), 0)\nPromise.resolve()\n  .then(() => console.log('micro 1'))\n  .then(() => console.log('micro 2'))\n\u002F\u002F micro 1, micro 2, macro\n\u002F\u002F Both microtasks finish before the timer, even with a 0ms delay.\n```\n\nThat \"microtasks always win\" behavior is why a resolved promise consistently\nbeats a `setTimeout(0)`.\n",{"id":1400,"difficulty":84,"q":1401,"a":1402},"ordering","What is the output order of this snippet?","```js\nconsole.log('A')\nsetTimeout(() => console.log('B'))\nPromise.resolve().then(() => console.log('C'))\nconsole.log('D')\n```\n\n**Output: `A D C B`.** Walk it through the way you would on a whiteboard:\n\n1. `console.log('A')` — synchronous, runs now -> **A**.\n2. `setTimeout(...)` — hands the callback to the timer API; it'll be queued as\n   a **macrotask**. Nothing prints yet.\n3. `Promise.resolve().then(...)` — schedules its callback as a **microtask**.\n   Nothing prints yet.\n4. `console.log('D')` — synchronous -> **D**.\n5. Script finishes, stack is empty -> drain **microtasks** -> **C**.\n6. Next macrotask runs -> **B**.\n\nThe takeaway: all synchronous code first, then every microtask, then the next\nmacrotask.\n",{"id":1404,"difficulty":63,"q":1405,"a":1406},"blocking","What happens if you run a long synchronous loop?","It **blocks the single thread**. While the loop runs the call stack never\nempties, so the event loop can't pull anything from the queues: timers don't\nfire on time, promise callbacks wait, clicks\u002Fscroll feel frozen, and the page\ncan't repaint (the dreaded \"page unresponsive\").\n\n```js\nconst end = Date.now() + 3000\nwhile (Date.now() \u003C end) {} \u002F\u002F freezes the tab for 3 full seconds\nconsole.log('finally free')\n```\n\nFixes: break the work into chunks that yield to the loop (`setTimeout`,\n`requestIdleCallback`), or move CPU-heavy work off the main thread into a **Web\nWorker** (browser) \u002F **Worker thread** (Node) so the UI stays responsive.\n",{"id":1408,"difficulty":84,"q":1409,"a":1410},"starvation","Can microtasks starve the event loop?","Yes. Because the engine drains the **whole** microtask queue before moving on,\na microtask that keeps scheduling more microtasks creates a queue that never\nempties — so macrotasks (timers, I\u002FO) and rendering are postponed\nindefinitely. The tab effectively hangs even though \"async\" code is running.\n\n```js\nfunction loop() {\n  queueMicrotask(loop) \u002F\u002F re-queues itself forever -> macrotasks never run\n}\nloop()\nsetTimeout(() => console.log('I will never print'), 0)\n```\n\nTo avoid starvation, yield to the macrotask queue for repeated\u002Flong work\n(`setTimeout`, `MessageChannel`, or `await` a real async boundary) so the loop\ngets a chance to run timers and paint frames between chunks.\n",{"id":1412,"difficulty":63,"q":1413,"a":1414},"queuemicrotask","What is queueMicrotask?","`queueMicrotask(fn)` schedules a callback to run as a **microtask** — after the\ncurrent synchronous code finishes but before the next macrotask. It's the direct\nway to queue a microtask without abusing `Promise.resolve().then()`.\n\n```js\nconsole.log('sync')\nqueueMicrotask(() => console.log('microtask'))\nconsole.log('sync 2')\n\u002F\u002F sync, sync 2, microtask\n```\n\nUse it to defer work to \"just after this task\" while still beating timers — e.g.\nbatching DOM reads or ensuring a callback runs after the current call stack\nunwinds but ASAP.\n",{"id":1416,"difficulty":84,"q":1417,"a":1418},"raf","How does requestAnimationFrame fit into the event loop?","`requestAnimationFrame(cb)` schedules `cb` to run **right before the next\nrepaint**, typically ~60 times per second. It's neither a macrotask nor a\nmicrotask — the browser runs rAF callbacks in a dedicated step of the rendering\npipeline, just before layout\u002Fpaint.\n\n```js\nrequestAnimationFrame(() => {\n  el.style.transform = `translateX(${x}px)` \u002F\u002F applied in sync with the frame\n})\n```\n\nUse it for animations and visual updates so they're synced to the display\nrefresh (no tearing, no wasted frames). Unlike `setTimeout`, it pauses in\nbackground tabs.\n",{"id":1420,"difficulty":63,"q":1421,"a":1422},"settimeout-clamp","Is setTimeout(fn, 0) really zero milliseconds?","No. `setTimeout(fn, 0)` means \"run as soon as possible **as a macrotask**,\" not\ninstantly. The HTML spec also **clamps** nested timeouts to a minimum (~4ms after\n5 levels of nesting), and the callback still waits for the stack to clear and all\nmicrotasks to drain.\n\n```js\nsetTimeout(() => console.log('timer'), 0)\nPromise.resolve().then(() => console.log('microtask'))\n\u002F\u002F microtask runs first — the \"0ms\" timer is still a macrotask\n```\n\nSo `setTimeout(0)` is \"defer to the next task,\" useful for yielding, but never a\nprecise or immediate timer.\n",{"id":1424,"difficulty":84,"q":1425,"a":1426},"node-vs-browser","How does the event loop differ between Node.js and the browser?","The core idea (stack + queues + microtask draining) is the same, but the\nimplementations differ:\n\n- The **browser** loop is defined by the HTML spec and integrates with\n  **rendering** (rAF, paint, layout).\n- **Node** uses **libuv** with distinct **phases** (timers, pending callbacks,\n  poll, check, close) and adds `process.nextTick` and `setImmediate`, with no\n  rendering step.\n\n```js\n\u002F\u002F Node-only ordering nuance:\nsetImmediate(() => console.log('immediate'))\nsetTimeout(() => console.log('timeout'), 0)\nprocess.nextTick(() => console.log('nextTick'))\n\u002F\u002F nextTick runs before both; immediate vs timeout order can vary\n```\n\nMicrotasks (promises) drain between phases\u002Ftasks in both environments.\n",{"id":1428,"difficulty":84,"q":1429,"a":1430},"nexttick","What is process.nextTick in Node and how does it differ from microtasks?","`process.nextTick(fn)` queues `fn` to run **after the current operation\ncompletes**, before the event loop continues — and crucially **before** the\nPromise microtask queue. So Node effectively has two micro-queues, with\n`nextTick` having higher priority.\n\n```js\nPromise.resolve().then(() => console.log('promise'))\nprocess.nextTick(() => console.log('nextTick'))\n\u002F\u002F nextTick, promise\n```\n\nBecause it preempts everything, recursively scheduling `nextTick` can **starve**\nthe loop entirely. Prefer `queueMicrotask`\u002Fpromises unless you specifically need\nits priority.\n",{"id":1432,"difficulty":84,"q":1433,"a":1434},"await-puzzle","What is the output order of this async\u002Fawait snippet?","```js\nconsole.log('1')\nasync function f() {\n  console.log('2')\n  await null\n  console.log('3')\n}\nf()\nconsole.log('4')\n\u002F\u002F Output: 1, 2, 4, 3\n```\n\n`f()` runs synchronously up to the `await` (logs **2**). `await` suspends the\nfunction and schedules the rest (`console.log('3')`) as a **microtask**, so\ncontrol returns to the caller and **4** logs. After the synchronous code, the\nmicrotask runs -> **3**. The body before the first `await` is synchronous; only\nwhat follows is deferred.\n",{"id":1436,"difficulty":84,"q":1437,"a":1438},"rendering-tasks","When does the browser render relative to tasks and microtasks?","The browser tries to render at most **once per frame** (~16.7ms at 60fps), and it\ndoes so **after** the current macrotask **and** its full microtask queue have\ncompleted — never in the middle of a task.\n\n```\nmacrotask -> drain microtasks -> (rAF callbacks) -> style\u002Flayout\u002Fpaint -> next macrotask\n```\n\nConsequence: synchronous DOM changes within one task aren't painted individually\n— only the final state shows. And a long task blocks rendering entirely, which is\nwhy long synchronous work freezes the page.\n",{"id":1440,"difficulty":84,"q":1441,"a":1442},"await-scheduling","How does await schedule the rest of an async function?","`await x` pauses the function and registers the **remaining code as a\ncontinuation** (a `.then` callback on `x`), which runs as a **microtask** once\n`x` settles. The async function is essentially rewritten into promise\ncontinuations by the engine.\n\n```js\nasync function g() {\n  const a = await fetchA() \u002F\u002F everything below becomes a microtask continuation\n  const b = await fetchB() \u002F\u002F ...and so does this, after a resolves\n  return a + b\n}\n```\n\nSo each `await` introduces a microtask boundary. This is why code after `await`\nalways runs after the current synchronous task, never inline.\n",{"id":1444,"difficulty":63,"q":1445,"a":1446},"settimeout-recursion","What is the difference between setInterval and recursive setTimeout?","`setInterval` queues the callback every N ms **regardless of how long it takes**\n— if the callback is slow, executions can pile up or overlap conceptually.\n**Recursive `setTimeout`** schedules the next run only **after** the current one\nfinishes, guaranteeing a gap.\n\n```js\n\u002F\u002F guarantees ≥1s between completions\nfunction poll() {\n  doWork()\n  setTimeout(poll, 1000)\n}\nsetTimeout(poll, 1000)\n```\n\nRecursive `setTimeout` is preferred for variable-duration work and for adapting\nthe delay dynamically; `setInterval` is fine for short, fixed-cadence ticks.\n",{"id":1448,"difficulty":84,"q":1449,"a":1450},"promise-chain-order","How are chained .then callbacks ordered against each other?","Each `.then` schedules its callback as a **separate microtask**, queued only when\nthe previous link resolves. So two independent chains **interleave** one\nmicrotask at a time.\n\n```js\nPromise.resolve().then(() => console.log('A1')).then(() => console.log('A2'))\nPromise.resolve().then(() => console.log('B1')).then(() => console.log('B2'))\n\u002F\u002F A1, B1, A2, B2\n```\n\n`A1` and `B1` are queued first; running `A1` queues `A2`, running `B1` queues\n`B2`. The engine drains the queue in FIFO order, producing the interleaving.\n",{"id":1452,"difficulty":63,"q":1453,"a":1454},"yield-main-thread","How do you yield to the event loop to keep the UI responsive?","Break long synchronous work into chunks and **schedule the next chunk as a\nmacrotask** so the loop can run timers, handle input, and paint in between.\n\n```js\nfunction processChunk(i) {\n  const end = Math.min(i + 1000, data.length)\n  for (; i \u003C end; i++) handle(data[i])\n  if (i \u003C data.length) setTimeout(() => processChunk(i), 0) \u002F\u002F yield\n}\nprocessChunk(0)\n```\n\nModern options include `scheduler.yield()`, `MessageChannel`, or\n`requestIdleCallback`. For pure CPU work, a **Web Worker** keeps the main thread\nfree entirely.\n",{"id":1456,"difficulty":84,"q":1457,"a":1458},"node-phases","What are the phases of the Node.js event loop?","libuv runs the loop through ordered phases, each with its own callback queue:\n\n1. **timers** — `setTimeout`\u002F`setInterval` callbacks.\n2. **pending callbacks** — deferred I\u002FO callbacks.\n3. **poll** — retrieve new I\u002FO events; execute I\u002FO callbacks.\n4. **check** — `setImmediate` callbacks.\n5. **close** — `close` event callbacks.\n\nBetween **every** phase, Node drains `process.nextTick` and the microtask\n(promise) queues. This phased structure is why `setImmediate` (check) and\n`setTimeout(0)` (timers) can fire in different orders depending on context.\n",{"id":1460,"difficulty":84,"q":1461,"a":1462},"setimmediate","What is the difference between setImmediate and setTimeout(0) in Node?","`setImmediate` runs in the **check** phase, after the **poll** phase, while\n`setTimeout(0)` runs in the **timers** phase at the start of the next loop. Inside\nan **I\u002FO callback**, `setImmediate` is deterministically first; at the top level\ntheir order is non-deterministic.\n\n```js\nconst fs = require('fs')\nfs.readFile(__filename, () => {\n  setTimeout(() => console.log('timeout'), 0)\n  setImmediate(() => console.log('immediate'))\n  \u002F\u002F inside I\u002FO: \"immediate\" always logs first\n})\n```\n\nRule: to run \"after the current I\u002FO, ASAP,\" use `setImmediate`.\n",{"id":1464,"difficulty":63,"q":1465,"a":1466},"promise-executor-sync","Does the Promise executor function run synchronously?","Yes. The function you pass to `new Promise((resolve, reject) => {...})` runs\n**synchronously, immediately**, as part of constructing the promise. Only the\n`.then`\u002F`.catch` **callbacks** are asynchronous (microtasks).\n\n```js\nconsole.log('start')\nnew Promise(resolve => {\n  console.log('executor')   \u002F\u002F runs now, synchronously\n  resolve()\n}).then(() => console.log('then'))\nconsole.log('end')\n\u002F\u002F start, executor, end, then\n```\n\nA common misconception is that everything about a promise is async — the executor\nbody is not.\n",{"id":1468,"difficulty":63,"q":1469,"a":1470},"await-nonpromise","What happens when you await a non-promise value?","`await` wraps any non-promise in `Promise.resolve(value)`, so the value comes back\nas-is — but the function **still suspends for one microtask tick**. So even\n`await 5` defers the rest of the function.\n\n```js\nasync function f() {\n  console.log('before')\n  await 5            \u002F\u002F not a promise, but still yields a microtask\n  console.log('after')\n}\nf()\nconsole.log('sync')\n\u002F\u002F before, sync, after\n```\n\nSo `await` always introduces an async boundary, even for plain values — handy to\nknow for ordering puzzles.\n",{"id":1472,"difficulty":63,"q":1473,"a":1474},"async-not-multithread","Does asynchronous code mean JavaScript is multithreaded?","No. JavaScript runs on a **single thread**; async just means work is **scheduled**\nto run later rather than blocking. The *waiting* (timers, network, file I\u002FO)\nhappens outside the JS engine (in the browser\u002FOS\u002Flibuv), but your callbacks all\nrun one-at-a-time on the same thread.\n\n```js\nsetTimeout(() => console.log('later'), 1000) \u002F\u002F the timer is handled elsewhere;\n\u002F\u002F the callback still runs on the single JS thread when the stack is free\n```\n\nTrue parallelism in JS requires **Web Workers** \u002F **worker threads**, which run\nseparate threads communicating via messages.\n",{"id":1476,"difficulty":71,"q":1477,"a":1478},"why-single-thread","Why is JavaScript single-threaded?","JavaScript was designed single-threaded to keep the **DOM model simple** — if\nmultiple threads could mutate the DOM concurrently, you'd need locks everywhere\nand face race conditions on every UI update. A single thread plus the event loop\ngives concurrency (handling many things) without the complexity of parallelism.\n\n```js\n\u002F\u002F no data races: only one piece of JS touches `count` at a time\nlet count = 0\nbutton.onclick = () => count++\n```\n\nThe trade-off is that CPU-heavy work blocks everything — solved by offloading to\nWeb Workers when needed.\n",{"id":1480,"difficulty":71,"q":1481,"a":1482},"callback-queue","What is the callback (task) queue?","The callback queue (a.k.a. task\u002Fmacrotask queue) holds callbacks that are\n**ready to run** but waiting for the call stack to clear — completed timers,\nresolved I\u002FO, dispatched events. The event loop moves one of them onto the stack\neach iteration.\n\n```js\nbutton.addEventListener('click', handler) \u002F\u002F handler is queued when clicked\nsetTimeout(cb, 100)                        \u002F\u002F cb is queued ~100ms later\n```\n\nIt's strictly FIFO per task source, and the loop only pulls from it when the\nstack is empty and microtasks are drained.\n",{"id":1484,"difficulty":84,"q":1485,"a":1486},"nested-timeout-order","What is the order of nested setTimeout and promise callbacks?","```js\nsetTimeout(() => {\n  console.log('timeout 1')\n  Promise.resolve().then(() => console.log('promise in timeout'))\n}, 0)\nsetTimeout(() => console.log('timeout 2'), 0)\n\u002F\u002F timeout 1, promise in timeout, timeout 2\n```\n\nEach macrotask is followed by a **full microtask drain** before the next\nmacrotask. So after \"timeout 1\" runs, its queued promise microtask executes\n**before** \"timeout 2\". This \"microtasks between every macrotask\" rule is the key\nto these puzzles.\n",{"id":1488,"difficulty":84,"q":1489,"a":1490},"microtask-checkpoint","What is a microtask checkpoint?","A microtask checkpoint is the point where the engine **drains the entire\nmicrotask queue**. It happens after the current macrotask completes (the stack\nempties) and also after certain operations like a callback returning. All pending\nmicrotasks — and any they schedule — run to completion before the next macrotask\nor render.\n\n```js\n\u002F\u002F everything queued via .then\u002FqueueMicrotask runs at the next checkpoint,\n\u002F\u002F before any setTimeout callback\n```\n\nUnderstanding checkpoints explains why microtasks always \"win\" and why they can\nstarve the loop if they keep scheduling more.\n",{"id":1492,"difficulty":84,"q":1493,"a":1494},"ordering-puzzle2","Trace the output of mixed sync, await, promise and setTimeout.","```js\nconsole.log('A')\nsetTimeout(() => console.log('B'), 0)\nPromise.resolve().then(() => console.log('C'))\n;(async () => {\n  console.log('D')\n  await null\n  console.log('E')\n})()\nconsole.log('F')\n\u002F\u002F A, D, F, C, E, B\n```\n\nSync first: **A**, then the async IIFE runs to its `await` -> **D**, then **F**.\nMicrotasks drain next: **C** (queued before the await continuation), then **E**.\nFinally the macrotask: **B**. Order of microtasks follows the order they were\nqueued.\n",{"id":1496,"difficulty":63,"q":1497,"a":1498},"input-responsiveness","How do long tasks hurt responsiveness (INP)?","A \"long task\" (>50ms of synchronous work) monopolizes the single thread, so the\nevent loop can't process the click\u002Fkeypress callback or repaint — the user\nperceives lag. This directly worsens the **INP (Interaction to Next Paint)**\nmetric.\n\n```js\nbutton.onclick = () => {\n  heavyCompute() \u002F\u002F blocks -> the visual response is delayed\n}\n```\n\nFixes: break work into chunks that yield, defer non-urgent work\n(`requestIdleCallback`), debounce, or move computation to a Web Worker so input\nhandling and painting stay snappy.\n",{"id":1500,"difficulty":63,"q":1501,"a":1502},"raf-vs-timeout-animation","Why use requestAnimationFrame instead of setTimeout for animation?","`requestAnimationFrame` runs **in sync with the display refresh** (right before\npaint) and **pauses in background tabs**, so animations are smooth and don't waste\nCPU\u002Fbattery. `setTimeout` fires on an arbitrary schedule unrelated to the frame,\ncausing dropped or doubled frames and jank.\n\n```js\nfunction animate() {\n  move()\n  requestAnimationFrame(animate) \u002F\u002F one update per frame, perfectly timed\n}\nrequestAnimationFrame(animate)\n```\n\nrAF also self-throttles to the screen's refresh rate, whereas a fixed\n`setTimeout(16)` drifts and can't adapt to 120Hz displays.\n",{"id":1504,"difficulty":63,"q":1505,"a":1506},"one-macrotask-per-tick","Why does the loop process only one macrotask per iteration?","Running one macrotask then draining microtasks (and giving rendering a chance)\nkeeps the system **responsive and fair**: it prevents a flood of queued tasks\nfrom blocking input handling and painting, and ensures microtask-based work\n(promises) completes promptly between tasks.\n\n```\n[1 macrotask] -> [all microtasks] -> [maybe render] -> [1 macrotask] -> ...\n```\n\nIf the loop drained the whole macrotask queue at once, a burst of timers\u002Fevents\ncould lock out rendering and user input until they all finished.\n",{"id":1508,"difficulty":71,"q":1509,"a":1510},"sync-vs-async-diff","What is the difference between synchronous and asynchronous code?","**Synchronous** code runs top-to-bottom, each statement **blocking** until it\nfinishes. **Asynchronous** code starts an operation and **continues without\nwaiting**, handling the result later via a callback\u002Fpromise — so the thread isn't\nblocked.\n\n```js\nconst data = readFileSync('f.txt') \u002F\u002F sync: blocks here until done\nreadFile('f.txt', (e, data) => {}) \u002F\u002F async: returns immediately, callback later\n```\n\nAsync is essential in single-threaded JS so that slow I\u002FO (network, disk) doesn't\nfreeze the UI — the event loop schedules the continuation when the result is\nready.\n",{"id":1512,"difficulty":84,"q":1513,"a":1514},"workers-offload","How do Web Workers relate to the event loop?","A Web Worker runs JavaScript on a **separate thread with its own event loop**, so\nCPU-heavy work there doesn't block the main thread's loop (and thus the UI). They\ncommunicate via `postMessage`, which queues a **message-event** (macrotask) on\nthe receiving side.\n\n```js\nconst worker = new Worker('heavy.js')\nworker.postMessage(bigData)\nworker.onmessage = e => render(e.data) \u002F\u002F runs on main thread when free\n```\n\nWorkers don't share memory by default (except `SharedArrayBuffer`), avoiding data\nraces. Use them to keep the main loop free for input and rendering.\n",{"id":1516,"difficulty":63,"q":1517,"a":1518},"defer-with-tasks","How can you defer work to the next tick using the event loop?","To run something **after** the current synchronous code without blocking, schedule\nit on a queue. The choice of queue controls priority:\n\n```js\nqueueMicrotask(fn)        \u002F\u002F ASAP: before the next render\u002Fmacrotask\nPromise.resolve().then(fn) \u002F\u002F also a microtask\nsetTimeout(fn, 0)          \u002F\u002F next macrotask (after microtasks + maybe a paint)\nrequestAnimationFrame(fn)  \u002F\u002F before the next paint\n```\n\nPick a **microtask** when the deferral must beat rendering\u002Ftimers, and a\n**macrotask** when you want to yield the thread (let input\u002Fpaint happen) before\ncontinuing.\n",{"description":61},"JavaScript event loop interview questions — the call stack, task and microtask queues, and how asynchronous code is scheduled.","javascript\u002Fasync\u002Fevent-loop","The Event Loop","Asynchronous JavaScript","async","2026-06-17","v5VF_8JManXxxPa5kLV8PcWEglG8nn9bwl29BN9yPxg",{"id":1528,"title":1529,"body":1530,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":1534,"navigation":66,"order":12,"path":1535,"questions":1536,"related":207,"seo":1672,"seoDescription":1673,"stem":1674,"subtopic":1675,"topic":1523,"topicSlug":1524,"updated":1525,"__hash__":1676},"qa\u002Fjavascript\u002Fasync\u002Fpromises.md","Promises",{"type":58,"value":1531,"toc":1532},[],{"title":61,"searchDepth":22,"depth":22,"links":1533},[],{},"\u002Fjavascript\u002Fasync\u002Fpromises",[1537,1541,1545,1549,1553,1557,1561,1565,1569,1572,1576,1580,1584,1588,1592,1596,1600,1604,1608,1612,1616,1620,1624,1628,1632,1636,1640,1644,1648,1652,1656,1660,1664,1668],{"id":1538,"difficulty":71,"q":1539,"a":1540},"what-is-promise","What is a Promise?","A Promise is an object representing the **eventual** result of an asynchronous\noperation — a placeholder for a value you don't have yet. It lives in one of\nthree states:\n\n- `pending` — the starting state, not yet settled.\n- `fulfilled` — completed successfully, carries a value.\n- `rejected` — failed, carries a reason (usually an `Error`).\n\n```js\nconst p = new Promise((resolve, reject) => {\n  setTimeout(() => resolve('done'), 100) \u002F\u002F settles after 100ms\n})\np.then(value => console.log(value)) \u002F\u002F 'done'\n```\n\nTwo properties make promises predictable: they're **settled once** (a\npending promise transitions to fulfilled *or* rejected exactly one time and\nthen its state\u002Fvalue are **immutable**), and `.then`\u002F`.catch` always run\n**asynchronously** as microtasks — never synchronously, even for an\nalready-resolved promise.\n",{"id":1542,"difficulty":63,"q":1543,"a":1544},"async-await","What is async\u002Fawait and how does it relate to promises?","`async`\u002F`await` is **syntactic sugar over promises** — it doesn't add new\ncapabilities, it makes promise code read like ordinary sequential code. Two\nrules: an `async` function **always returns a promise** (any value you return\nis wrapped in a resolved promise; any throw becomes a rejected one), and\n`await` **pauses** the function until the awaited promise settles, then\nresumes with its value.\n\n```js\nasync function load() {\n  const res = await fetch('\u002Fapi')   \u002F\u002F pause until the request resolves\n  return res.json()                 \u002F\u002F also awaited by the caller\n}\nload().then(data => console.log(data)) \u002F\u002F still a promise underneath\n```\n\nCrucially, `await` only suspends the *current async function* — the rest of\nthe program keeps running. Under the hood the code after an `await` becomes a\n`.then` continuation scheduled as a microtask.\n",{"id":1546,"difficulty":63,"q":1547,"a":1548},"error-handling","How do you handle errors with promises and async\u002Fawait?","With raw promises, attach `.catch()` to handle a rejection anywhere up the\nchain. With `async`\u002F`await`, an awaited rejected promise **throws**, so you use\na normal `try\u002Fcatch`.\n\n```js\n\u002F\u002F promise style\nload().then(use).catch(err => console.error(err))\n\n\u002F\u002F async\u002Fawait style — reads like synchronous try\u002Fcatch\ntry {\n  const data = await load()\n  use(data)\n} catch (err) {\n  console.error(err)\n} finally {\n  hideSpinner() \u002F\u002F runs whether it succeeded or failed\n}\n```\n\nGotchas interviewers probe: a single `.catch()` at the end catches errors from\n*every* prior step in the chain; an **unhandled** rejection triggers an\n`unhandledrejection` event\u002Fwarning; and forgetting to `await` (or `return`) a\npromise inside a `try` means its rejection escapes the `catch` entirely.\n",{"id":1550,"difficulty":63,"q":1551,"a":1552},"promise-all","What is the difference between Promise.all and Promise.allSettled?","Both take an iterable of promises and run them concurrently, but they differ in\nhow they handle failure:\n\n- `Promise.all` **short-circuits**: it fulfills with an array of all values\n  once **every** promise fulfills, but rejects **immediately** the moment\n  **any one** rejects — you lose the results of the others.\n- `Promise.allSettled` **never rejects**: it waits for **every** promise to\n  settle and resolves with an array of `{ status, value }` or\n  `{ status, reason }` objects, so you can inspect each outcome.\n\n```js\nconst results = await Promise.allSettled([fetchA(), fetchB(), fetchC()])\nresults.forEach(r => {\n  if (r.status === 'fulfilled') console.log('ok', r.value)\n  else console.log('failed', r.reason)\n})\n```\n\nReach for `all` when you need *all-or-nothing* (one failure should abort);\nreach for `allSettled` when you want every result regardless of partial\nfailures (e.g. a dashboard of independent widgets).\n",{"id":1554,"difficulty":63,"q":1555,"a":1556},"promise-race","What do Promise.race and Promise.any do?","Both settle based on the **first** promise to finish, but they disagree on what\ncounts:\n\n- `Promise.race` settles as soon as the first promise **settles** — whether it\n  fulfills *or* rejects. The first one to cross the line wins, error or not.\n- `Promise.any` resolves with the first promise to **fulfill**, ignoring\n  rejections. It only rejects if **all** of them reject, with an\n  `AggregateError` bundling every reason.\n\n```js\n\u002F\u002F timeout pattern — race the work against a timer\nconst data = await Promise.race([\n  fetch('\u002Fapi'),\n  new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 5000)),\n])\n\n\u002F\u002F first successful mirror wins; only fails if every mirror is down\nconst fastest = await Promise.any([fetch(mirror1), fetch(mirror2)])\n```\n\nMnemonic: **race** cares about *first to finish*, **any** cares about *first to\nsucceed*.\n",{"id":1558,"difficulty":84,"q":1559,"a":1560},"sequential-parallel","How do you run async tasks in parallel vs sequentially?","The difference is **when you start** each task. `await` inside a loop starts\nthe next task only after the previous one resolves — that's **sequential** and\noften an accidental performance bug. To go **parallel**, kick them all off\nfirst (so they run concurrently), then `await` them together.\n\n```js\n\u002F\u002F sequential: ~A + B + C total time\nfor (const url of urls) {\n  results.push(await fetch(url))\n}\n\n\u002F\u002F parallel: ~max(A, B, C) total time\nconst results = await Promise.all(urls.map(url => fetch(url)))\n```\n\nUse sequential intentionally when each step **depends on the previous one's\nresult** or you must avoid hammering a rate-limited API. Use parallel when the\ntasks are independent — it can be dramatically faster.\n",{"id":1562,"difficulty":84,"q":1563,"a":1564},"microtask","Why does an awaited promise callback run before a setTimeout?","Because promise continuations are scheduled as **microtasks**, while\n`setTimeout` callbacks are **macrotasks** — and the event loop drains the\n*entire* microtask queue after the current synchronous code, *before* it ever\nreaches the next macrotask.\n\n```js\nconsole.log(1)\nsetTimeout(() => console.log(2), 0)        \u002F\u002F macrotask\nPromise.resolve().then(() => console.log(3)) \u002F\u002F microtask\nconsole.log(4)\n\u002F\u002F Output: 1, 4, 3, 2 — the promise (3) beats the timer (2)\n```\n\nSo even `setTimeout(fn, 0)` is effectively \"run after all pending microtasks,\"\nwhich is why a resolved promise's `.then` always fires first.\n",{"id":1566,"difficulty":63,"q":1567,"a":1568},"promisify","How do you convert a callback-based API to a promise?","Wrap the callback API in `new Promise(...)` and translate the callback's\noutcome into `resolve`\u002F`reject`. For Node-style `(err, value)` callbacks, the\nconvention is \"error first\": reject on `err`, otherwise resolve with the value.\n\n```js\n\u002F\u002F simple timer\nconst wait = ms => new Promise(resolve => setTimeout(resolve, ms))\n\n\u002F\u002F wrapping a Node-style error-first callback\nconst readFileAsync = path =>\n  new Promise((resolve, reject) => {\n    fs.readFile(path, 'utf8', (err, data) => {\n      if (err) reject(err)\n      else resolve(data)\n    })\n  })\n```\n\nIn Node you'd usually reach for the built-in `util.promisify` instead of\nhand-rolling this, but interviewers like to see you can build it from scratch.\n",{"id":892,"difficulty":63,"q":1570,"a":1571},"How does promise chaining work?","Each `.then` returns a **new promise** that resolves with whatever its callback\nreturns, so you can chain steps where each receives the previous result. This\nflattens nested callbacks into a linear sequence.\n\n```js\nfetch('\u002Fapi\u002Fuser')\n  .then(res => res.json())     \u002F\u002F returns parsed body\n  .then(user => fetch(`\u002Fapi\u002Fposts\u002F${user.id}`))\n  .then(res => res.json())\n  .then(posts => console.log(posts))\n  .catch(err => console.error(err))\n```\n\nThe chain runs step by step; returning a value passes it down, returning a\npromise waits for it. A single trailing `.catch` handles errors from any step.\n",{"id":1573,"difficulty":63,"q":1574,"a":1575},"then-return-value","What does .then return and why does it matter?","`.then` always returns a **new promise**. What that promise resolves to depends on\nthe callback: a plain value -> resolves with it; a promise -> **adopts** that\npromise's eventual value (flattening); a `throw` -> rejects.\n\n```js\nPromise.resolve(1)\n  .then(x => x + 1)               \u002F\u002F resolves 2\n  .then(x => Promise.resolve(x*10)) \u002F\u002F resolves 20 (adopted)\n  .then(x => { throw new Error() }) \u002F\u002F rejects\n  .then(x => console.log('skipped'))\n  .catch(() => console.log('caught'))\n```\n\nBecause each `.then` is a fresh promise, chaining and error propagation \"just\nwork\" — and forgetting to **return** inside a `.then` breaks the chain (the next\nstep gets `undefined`).\n",{"id":1577,"difficulty":63,"q":1578,"a":1579},"catch-chain","Where should you place .catch in a chain?","Usually a **single `.catch` at the end** of the chain — it handles a rejection\nfrom **any** preceding step, because errors propagate down until caught. Place an\nintermediate `.catch` only if you want to **recover** and continue the chain.\n\n```js\nstep1().then(step2).then(step3)\n  .catch(err => console.error('any step failed', err))\n\n\u002F\u002F recover mid-chain:\nload().catch(() => fallback()).then(use) \u002F\u002F continues with fallback's value\n```\n\nA `.catch` that returns a value produces a **resolved** promise, so the chain\ncontinues normally after recovery.\n",{"id":1581,"difficulty":71,"q":1582,"a":1583},"finally-block","What does .finally do?","`.finally(cb)` runs `cb` **whether the promise fulfilled or rejected** — for\ncleanup that should always happen (hide a spinner, close a connection). It\nreceives **no argument** and, importantly, **passes the original value\u002Ferror\nthrough** unchanged.\n\n```js\nshowSpinner()\nfetchData()\n  .then(use)\n  .catch(handle)\n  .finally(() => hideSpinner()) \u002F\u002F always runs, doesn't alter the result\n```\n\nCaveat: if `.finally`'s callback itself throws or returns a rejected promise, it\n*does* override the outcome — but a normal return is ignored.\n",{"id":1585,"difficulty":84,"q":1586,"a":1587},"unhandled-rejection","What is an unhandled promise rejection?","A rejected promise with **no `.catch`** (or no `try\u002Fcatch` around its `await`) is\n\"unhandled.\" Browsers fire an `unhandledrejection` event and log a warning; Node\nprints a warning and (in recent versions) **crashes the process** by default.\n\n```js\nPromise.reject(new Error('boom')) \u002F\u002F no handler -> unhandled rejection\n\nwindow.addEventListener('unhandledrejection', e => {\n  console.error('unhandled:', e.reason)\n  e.preventDefault()\n})\n```\n\nAlways attach a `.catch` or wrap awaits in `try\u002Fcatch`. A global handler is a\nsafety net for logging, not a substitute for handling errors at the source.\n",{"id":1589,"difficulty":71,"q":1590,"a":1591},"resolve-reject-static","What do Promise.resolve and Promise.reject do?","They create **already-settled** promises: `Promise.resolve(v)` returns a promise\nfulfilled with `v` (or adopts `v` if it's already a promise\u002Fthenable), and\n`Promise.reject(e)` returns one rejected with `e`. Handy for returning a\nconsistent promise type or starting a chain.\n\n```js\nfunction getUser(id) {\n  const cached = cache.get(id)\n  if (cached) return Promise.resolve(cached) \u002F\u002F sync value as a promise\n  return fetch(`\u002Fapi\u002F${id}`).then(r => r.json())\n}\n```\n\n`Promise.resolve` is also how `await` wraps non-promise values, and how you\nnormalize \"maybe a value, maybe a promise\" into always-a-promise.\n",{"id":1593,"difficulty":84,"q":1594,"a":1595},"thenable","What is a thenable?","A thenable is **any object with a `.then(resolve, reject)` method**. The promise\nmachinery treats thenables like promises — `await` and `Promise.resolve` will\n\"follow\" a thenable by calling its `then`. This is what makes different promise\nlibraries interoperate.\n\n```js\nconst thenable = {\n  then(resolve) { resolve(42) }\n}\nPromise.resolve(thenable).then(v => console.log(v)) \u002F\u002F 42\nawait thenable                                       \u002F\u002F 42\n```\n\nIt's why returning a thenable from `.then` flattens it. The downside: any object\nthat *happens* to have a `then` method gets treated specially — a rare source of\nsurprises.\n",{"id":1597,"difficulty":63,"q":1598,"a":1599},"throw-in-then","What happens if you throw inside a .then callback?","Throwing inside a `.then` (or `.catch`) callback **rejects** the promise that\n`.then` returns, so the error skips subsequent `.then`s and is caught by the next\n`.catch` down the chain.\n\n```js\nPromise.resolve()\n  .then(() => { throw new Error('fail') })\n  .then(() => console.log('skipped'))      \u002F\u002F not run\n  .catch(err => console.log('caught:', err.message)) \u002F\u002F caught: fail\n```\n\nThis is what makes promise error handling feel like synchronous `try\u002Fcatch` — a\nthrown error propagates to the nearest handler instead of crashing.\n",{"id":1601,"difficulty":63,"q":1602,"a":1603},"return-promise-then","What happens when you return a promise from .then?","The outer chain **waits** for that returned promise to settle and adopts its\nresult — this is \"flattening.\" It's how you sequence async steps without nesting.\n\n```js\ngetUser()\n  .then(user => fetchPosts(user.id)) \u002F\u002F returns a promise\n  .then(posts => console.log(posts)) \u002F\u002F runs only after fetchPosts resolves\n```\n\nPromises never nest as `Promise\u003CPromise\u003CT>>`; returning a promise from `.then`\nauto-unwraps it. Forgetting to **return** it, though, means the next step runs\nimmediately with `undefined`.\n",{"id":1605,"difficulty":63,"q":1606,"a":1607},"nested-vs-flat","How do you flatten nested .then callbacks?","Nesting `.then`s recreates callback hell. Because returning a promise flattens the\nchain, you can keep it **flat** by returning instead of nesting.\n\n```js\n\u002F\u002F nested (\"promise hell\")\na().then(x => {\n  b(x).then(y => {\n    c(y).then(z => console.log(z))\n  })\n})\n\u002F\u002F flat\na().then(b).then(c).then(z => console.log(z))\n```\n\n`async\u002Fawait` flattens it even more readably. Nesting is occasionally needed when\nan inner step requires an **outer** value, but usually a flat chain (or await)\navoids it.\n",{"id":1609,"difficulty":84,"q":1610,"a":1611},"reduce-sequential","How do you run promises sequentially using reduce?","Chain them by reducing over an array, where each step awaits the accumulator\npromise before starting — guaranteeing order and one-at-a-time execution.\n\n```js\nconst urls = ['\u002Fa', '\u002Fb', '\u002Fc']\nawait urls.reduce(\n  (chain, url) => chain.then(() => fetch(url)),\n  Promise.resolve()\n)\n\u002F\u002F or with await in a for...of:\nfor (const url of urls) await fetch(url)\n```\n\nUse this when each request must finish before the next (ordering, rate limits,\ndependencies). For independent requests, `Promise.all` is faster.\n",{"id":1613,"difficulty":84,"q":1614,"a":1615},"concurrency-limit","How do you limit the concurrency of many async tasks?","Running thousands of requests at once with `Promise.all` can overwhelm a server\nor hit rate limits. Cap the number in flight with a **worker pool**: N workers\npulling from a shared queue.\n\n```js\nasync function pool(items, limit, fn) {\n  const results = []\n  const queue = [...items.entries()]\n  async function worker() {\n    for (const [i, item] of queue.splice(0)) results[i] = await fn(item)\n  }\n  await Promise.all(Array.from({ length: limit }, worker))\n  return results\n}\nawait pool(urls, 5, fetch) \u002F\u002F at most 5 concurrent requests\n```\n\nLibraries like `p-limit` provide this off the shelf. The idea: parallelism, but\n**bounded**.\n",{"id":1617,"difficulty":84,"q":1618,"a":1619},"retry-backoff","How do you implement retry with exponential backoff?","Wrap the operation in a loop that catches failures and waits an increasing delay\nbefore retrying, up to a max attempt count.\n\n```js\nasync function retry(fn, attempts = 3, delay = 200) {\n  for (let i = 0; i \u003C attempts; i++) {\n    try {\n      return await fn()\n    } catch (err) {\n      if (i === attempts - 1) throw err\n      await new Promise(r => setTimeout(r, delay * 2 ** i)) \u002F\u002F 200, 400, 800...\n    }\n  }\n}\n```\n\nExponential backoff (often with jitter) avoids hammering a struggling service.\nOnly retry **idempotent**\u002Ftransient failures — retrying a non-idempotent write\ncan duplicate effects.\n",{"id":1621,"difficulty":63,"q":1622,"a":1623},"for-await-of","What is for await...of and when do you use it?","`for await...of` iterates an **async iterable** (or an iterable of promises),\nawaiting each value in turn — ideal for consuming streams or paginated APIs\nsequentially.\n\n```js\nfor await (const chunk of readableStream) {\n  process(chunk) \u002F\u002F each chunk awaited in order\n}\n\nfor await (const value of [fetch('\u002Fa'), fetch('\u002Fb')]) {\n  console.log(value) \u002F\u002F awaits each promise sequentially\n}\n```\n\nIt processes items **one at a time** (sequential). For concurrent processing of\na fixed array, `Promise.all(arr.map(...))` is the right tool instead.\n",{"id":1625,"difficulty":63,"q":1626,"a":1627},"top-level-await","What is top-level await?","In **ES modules**, you can use `await` at the **top level**, outside any async\nfunction. The module's evaluation pauses until the awaited promise settles, and\nimporters wait for it.\n\n```js\n\u002F\u002F config.mjs\nconst res = await fetch('\u002Fconfig.json')\nexport const config = await res.json()\n```\n\nIt's great for module initialization (loading config, dynamic imports,\nconnecting). Caveat: it can **delay** the loading of dependent modules, so avoid\nslow top-level awaits in widely-imported modules. Not available in CommonScript\nscripts.\n",{"id":1629,"difficulty":84,"q":1630,"a":1631},"cancellation","How do you cancel a promise or async operation?","Promises themselves **can't be cancelled** — once started they run to settlement.\nThe standard approach is an **`AbortController`**: pass its `signal` to\ncancellable APIs (`fetch`, timers) and call `abort()` to stop them.\n\n```js\nconst ctrl = new AbortController()\nfetch('\u002Fslow', { signal: ctrl.signal })\n  .catch(e => { if (e.name === 'AbortError') console.log('cancelled') })\nctrl.abort() \u002F\u002F triggers an AbortError rejection\n```\n\nFor your own async functions, check `signal.aborted` at await points and bail\nout. The promise still settles (as a rejection); \"cancellation\" means stopping\nthe underlying work and ignoring the result.\n",{"id":1633,"difficulty":84,"q":1634,"a":1635},"await-in-foreach","Why doesn't await work inside forEach?","`Array.prototype.forEach` **ignores** the return value of its callback, so it\ndoesn't await the async callback's promise — the loop fires all callbacks and\nmoves on immediately, not waiting for any of them.\n\n```js\n\u002F\u002F does NOT wait; \"done\" logs before any item is processed\nitems.forEach(async item => { await process(item) })\nconsole.log('done')\n\n\u002F\u002F sequential\nfor (const item of items) await process(item)\n\u002F\u002F concurrent\nawait Promise.all(items.map(item => process(item)))\n```\n\nUse `for...of` (sequential) or `map` + `Promise.all` (concurrent). `forEach` is\nsimply not async-aware.\n",{"id":1637,"difficulty":84,"q":1638,"a":1639},"await-parallel-start","How do you start async tasks in parallel but await them later?","Call the async functions **first** (which starts them immediately) and store the\npromises, then `await` them afterward. The work overlaps because it began before\nany `await`.\n\n```js\nconst pa = fetchA() \u002F\u002F starts now\nconst pb = fetchB() \u002F\u002F starts now (concurrently)\nconst a = await pa  \u002F\u002F wait for both, but they already ran in parallel\nconst b = await pb\n```\n\nContrast with `const a = await fetchA(); const b = await fetchB()` which is\nsequential. `Promise.all([pa, pb])` is the cleaner equivalent and also propagates\nerrors as soon as one fails.\n",{"id":1641,"difficulty":63,"q":1642,"a":1643},"parallel-map-all","How do you process an array concurrently with Promise.all and map?","Map each element to a promise (starting all the work), then `Promise.all` to wait\nfor the whole batch and collect results **in order**.\n\n```js\nconst results = await Promise.all(\n  ids.map(id => fetchUser(id))\n)\n\u002F\u002F results[i] corresponds to ids[i], even if they resolved out of order\n```\n\nThis runs everything concurrently — far faster than awaiting in a loop. Beware\nunbounded concurrency for large arrays (use a concurrency limit), and remember\n`Promise.all` rejects as soon as **any** task fails.\n",{"id":1645,"difficulty":63,"q":1646,"a":1647},"explicit-construction-antipattern","What is the explicit promise construction antipattern?","Wrapping an **already-promise-returning** operation in `new Promise` is redundant,\nverbose, and easy to get wrong (forgetting to reject, swallowing errors). Just\nreturn\u002Fawait the existing promise.\n\n```js\n\u002F\u002F antipattern — wrapping a promise in a promise\nfunction load() {\n  return new Promise((resolve, reject) => {\n    fetch('\u002Fx').then(resolve).catch(reject)\n  })\n}\n\u002F\u002F just return it\nfunction load() { return fetch('\u002Fx') }\n```\n\nUse `new Promise` **only** to wrap a **callback-based** API that isn't already\npromisified.\n",{"id":1649,"difficulty":63,"q":1650,"a":1651},"async-vs-then-style","When should you use async\u002Fawait vs .then chains?","They're interchangeable, but `async\u002Fawait` usually reads better, especially with\nbranching, loops, and try\u002Fcatch error handling. `.then` chains shine for simple\nlinear transformations and point-free style.\n\n```js\n\u002F\u002F await: clearer with logic between steps\nasync function load() {\n  const user = await getUser()\n  if (!user.active) return null\n  return getPosts(user.id)\n}\n\u002F\u002F then: fine for a straight pipeline\nconst upper = () => fetch('\u002Fx').then(r => r.text()).then(t => t.toUpperCase())\n```\n\nMixing is fine. Prefer `await` for readability; just remember every `await`\nintroduces a microtask boundary.\n",{"id":1653,"difficulty":71,"q":1654,"a":1655},"promise-immutable","Can a promise change its state after settling?","No. A promise transitions **once** from `pending` to either `fulfilled` or\n`rejected`, and after that its state and value are **immutable**. Calling\n`resolve`\u002F`reject` again does nothing.\n\n```js\nconst p = new Promise((resolve, reject) => {\n  resolve('first')\n  resolve('second') \u002F\u002F ignored\n  reject('error')   \u002F\u002F ignored\n})\np.then(v => console.log(v)) \u002F\u002F 'first'\n```\n\nThis guarantee is what makes promises composable: once you have a settled\npromise, its result never changes, and adding more `.then`s later still gives you\nthat same value.\n",{"id":1657,"difficulty":63,"q":1658,"a":1659},"promise-all-empty","What does Promise.all([]) resolve to?","`Promise.all([])` resolves **immediately** with an **empty array** — there's\nnothing to wait for. The same edge case applies to `allSettled([])` (empty\narray). But `Promise.any([])` **rejects** with an `AggregateError` (nothing can\nfulfill), and `Promise.race([])` stays **pending forever**.\n\n```js\nawait Promise.all([])      \u002F\u002F []\nawait Promise.allSettled([]) \u002F\u002F []\nawait Promise.race([])     \u002F\u002F never settles\n```\n\nThese empty-array behaviors are classic gotchas — guard against an empty input\nlist if it could occur, especially for `race`\u002F`any`.\n",{"id":1661,"difficulty":63,"q":1662,"a":1663},"partial-failures","How do you handle partial failures across multiple async tasks?","Use **`Promise.allSettled`**, which waits for every task and reports each\noutcome, so one failure doesn't discard the successes (as `Promise.all` would).\n\n```js\nconst results = await Promise.allSettled(urls.map(fetch))\nconst ok = results.filter(r => r.status === 'fulfilled').map(r => r.value)\nconst failed = results.filter(r => r.status === 'rejected').map(r => r.reason)\n```\n\nThis is the right tool for dashboards, batch jobs, and \"best-effort\" operations\nwhere you want all results regardless of individual failures.\n",{"id":1665,"difficulty":63,"q":1666,"a":1667},"fire-and-forget","What are the risks of \"fire and forget\" promises?","Calling an async function without awaiting or attaching `.catch` (\"floating\npromise\") means errors become **unhandled rejections**, and you lose control over\nordering and completion.\n\n```js\n\u002F\u002F floating — errors vanish, no way to know when it's done\nsaveAnalytics(data)\n\n\u002F\u002F at least handle errors\nsaveAnalytics(data).catch(err => log(err))\n\u002F\u002F or await if the result\u002Fordering matters\nawait saveAnalytics(data)\n```\n\nIf you intentionally don't await, **always** attach a `.catch`. Linters\n(`no-floating-promises`) flag these because silent failures are hard to debug.\n",{"id":1669,"difficulty":63,"q":1670,"a":1671},"await-error-multiple","How do you handle errors across multiple awaits?","A single `try\u002Fcatch` around the awaits catches a rejection from **any** of them —\nexecution jumps to `catch` at the first failure, skipping the rest.\n\n```js\ntry {\n  const user = await getUser()\n  const posts = await getPosts(user.id)\n  const stats = await getStats(posts)\n} catch (err) {\n  \u002F\u002F catches whichever await rejected first\n  console.error(err)\n}\n```\n\nFor **independent** operations where you want all errors (not just the first),\nuse `Promise.allSettled` and inspect each result instead of letting the first\nrejection short-circuit.\n",{"description":61},"JavaScript promise and async\u002Fawait interview questions — states, chaining, error handling, Promise.all vs race, and converting callbacks.","javascript\u002Fasync\u002Fpromises","Promises & async\u002Fawait","qvoFc9byIt-vpMOLYR4_aXHuFSUm0hmc9QGBW5Vegyw",{"id":1678,"title":1679,"body":1680,"description":61,"difficulty":84,"extension":64,"framework":11,"frameworkSlug":9,"meta":1684,"navigation":66,"order":22,"path":1685,"questions":1686,"related":207,"seo":1783,"seoDescription":1784,"stem":1785,"subtopic":1786,"topic":1787,"topicSlug":1788,"updated":214,"__hash__":1789},"qa\u002Fjavascript\u002Fclasses\u002Fclass-inheritance.md","Class Inheritance",{"type":58,"value":1681,"toc":1682},[],{"title":61,"searchDepth":22,"depth":22,"links":1683},[],{},"\u002Fjavascript\u002Fclasses\u002Fclass-inheritance",[1687,1691,1695,1699,1703,1707,1711,1715,1719,1723,1727,1731,1735,1739,1743,1747,1751,1755,1759,1763,1767,1771,1775,1779],{"id":1688,"difficulty":71,"q":1689,"a":1690},"extends-keyword","How does the extends keyword work?","`class Child extends Parent` makes `Child` inherit from `Parent`: instances get\n`Parent`'s methods via the prototype chain, and `Child` itself inherits\n`Parent`'s statics.\n\n```js\nclass Animal {\n  constructor(name) { this.name = name }\n  speak() { return `${this.name} makes a sound` }\n}\nclass Dog extends Animal {\n  speak() { return `${this.name} barks` }\n}\nnew Dog('Rex').speak()   \u002F\u002F 'Rex barks'\n```\n\n`extends` wires up two chains: `Dog.prototype -> Animal.prototype` (instance\nmethods) and `Dog -> Animal` (statics). It's the clean syntax for the manual\nprototype linking you'd otherwise write.\n",{"id":1692,"difficulty":63,"q":1693,"a":1694},"super-constructor","What does super() do in a constructor?","It calls the **parent constructor**, initializing the inherited part of the\ninstance. In a derived class you **must** call `super()` before using `this`.\n\n```js\nclass Dog extends Animal {\n  constructor(name, breed) {\n    super(name)        \u002F\u002F run Animal's constructor first\n    this.breed = breed\n  }\n}\n```\n\nThe parent constructor actually creates `this` for a derived class, which is why\n`super()` must come first. If a subclass has no constructor, a default one\ncalls `super(...args)` automatically.\n",{"id":1696,"difficulty":63,"q":1697,"a":1698},"super-method","How do you call a parent method with super?","`super.method()` invokes the parent class's method with the current instance as\n`this` — for extending rather than fully replacing behavior.\n\n```js\nclass Dog extends Animal {\n  speak() {\n    return super.speak() + ' (woof)'   \u002F\u002F reuse parent, add to it\n  }\n}\n```\n\n`super` works in any method, getter, or static method — not just the\nconstructor. It resolves to the method on the *parent's* prototype, so overrides\ncan build on the inherited version.\n",{"id":1700,"difficulty":84,"q":1701,"a":1702},"this-before-super","Why does using this before super() throw?","In a derived class, the instance object is created by the parent constructor via\n`super()`. Until `super()` runs, `this` is uninitialized, so accessing it throws\na `ReferenceError`.\n\n```js\nclass Dog extends Animal {\n  constructor(name) {\n    this.x = 1     \u002F\u002F ReferenceError: must call super first\n    super(name)\n  }\n}\n```\n\nThis is a real semantic difference from constructor functions (where `this`\nexists immediately). The rule ensures the parent has fully set up the object\nbefore the child modifies it.\n",{"id":1704,"difficulty":71,"q":1705,"a":1706},"method-overriding","What is method overriding?","Defining a method in a subclass with the same name as the parent's — the\nsubclass version shadows the parent's for instances of the subclass.\n\n```js\nclass Shape { area() { return 0 } }\nclass Circle extends Shape {\n  constructor(r) { super(); this.r = r }\n  area() { return Math.PI * this.r ** 2 }   \u002F\u002F overrides Shape.area\n}\nnew Circle(2).area()   \u002F\u002F 12.56...\n```\n\nLookup finds the subclass method first. You can still reach the parent's version\nvia `super.area()`. Overriding is the basis of polymorphism.\n",{"id":1708,"difficulty":63,"q":1709,"a":1710},"polymorphism-js","How does polymorphism work with classes?","Different subclasses override the same method, and calling that method on a\nbase-typed reference runs the actual object's version (dynamic dispatch).\n\n```js\nclass Shape { area() { return 0 } }\nclass Circle extends Shape { area() { return Math.PI * this.r ** 2 } }\nclass Square extends Shape { area() { return this.s ** 2 } }\n\nconst shapes = [new Circle(), new Square()]\nshapes.forEach(s => console.log(s.area()))  \u002F\u002F each runs its own area()\n```\n\nJavaScript dispatches methods at runtime by the object's prototype, so a\n`Shape[]` can hold mixed subclasses and each responds with its own behavior —\nclassic polymorphism.\n",{"id":1712,"difficulty":63,"q":1713,"a":1714},"default-constructor","What is the default constructor in a subclass?","If a subclass omits a constructor, JavaScript inserts one that forwards all\narguments to the parent: `constructor(...args) { super(...args) }`.\n\n```js\nclass Animal { constructor(name) { this.name = name } }\nclass Dog extends Animal {}        \u002F\u002F implicit: constructor(...a){ super(...a) }\nnew Dog('Rex').name                \u002F\u002F 'Rex' — forwarded to Animal\n```\n\nSo you only need to write a subclass constructor when you add fields or change\nhow the parent is called. The default just chains to `super`.\n",{"id":1716,"difficulty":84,"q":1717,"a":1718},"super-in-static","Can you use super in static methods?","Yes — in a static method, `super.method()` calls the **parent class's** static\nmethod, because static members are inherited along the constructor's own\nprototype chain.\n\n```js\nclass Base { static create() { return 'base' } }\nclass Derived extends Base {\n  static create() { return super.create() + '-derived' }\n}\nDerived.create()   \u002F\u002F 'base-derived'\n```\n\nThis works because `Derived.__proto__ === Base`, so `super` in a static context\nresolves to `Base`. Static inheritance is a real and sometimes-surprising part\nof `extends`.\n",{"id":1720,"difficulty":84,"q":1721,"a":1722},"extends-builtins","How do you extend built-in classes like Array or Error?","Use `extends` directly — modern engines support subclassing built-ins, with\n`super()` initializing the built-in part.\n\n```js\nclass Stack extends Array {\n  peek() { return this[this.length - 1] }\n}\nconst s = new Stack()\ns.push(1, 2); s.peek()   \u002F\u002F 2 — inherits all Array methods\n\nclass AppError extends Error {\n  constructor(msg, code) { super(msg); this.name = 'AppError'; this.code = code }\n}\n```\n\nCaveat: extending `Error` historically needed `Object.setPrototypeOf(this,\nnew.target.prototype)` for correct `instanceof` after transpilation; native\nES6+ handles it. Extending `Array` also has subtle `length`\u002Findex behaviors.\n",{"id":1724,"difficulty":84,"q":1725,"a":1726},"abstract-class-pattern","How do you create an abstract class?","JavaScript has no `abstract` keyword, so you simulate it: throw if instantiated\ndirectly (`new.target`) and throw from methods subclasses must implement.\n\n```js\nclass Shape {\n  constructor() {\n    if (new.target === Shape) throw new Error('Shape is abstract')\n  }\n  area() { throw new Error('area() must be implemented') }\n}\nclass Circle extends Shape {\n  constructor(r) { super(); this.r = r }\n  area() { return Math.PI * this.r ** 2 }\n}\n```\n\n`new.target === Shape` blocks direct instantiation; unimplemented methods throw\nat call time. It's a convention, not a language feature.\n",{"id":1728,"difficulty":63,"q":1729,"a":1730},"inheritance-vs-composition-class","When should you prefer composition over class inheritance?","Favor composition when behavior is orthogonal or shared across unrelated types,\nor when a deep hierarchy would become rigid. Use inheritance for genuine is-a\nrelationships with stable base classes.\n\n```js\n\u002F\u002F inheritance forcing a hierarchy\nclass FlyingSwimmingDuck extends Animal {}\n\n\u002F\u002F compose capabilities\nconst duck = { ...canFly(), ...canSwim(), name: 'Donald' }\n```\n\nDeep inheritance suffers from the fragile-base-class problem; composition (mixins,\ndelegation, functions) stays flexible. \"Favor composition over inheritance\"\napplies strongly in JS.\n",{"id":1732,"difficulty":84,"q":1733,"a":1734},"super-property-access","Can super access parent getters and fields?","`super` accesses parent **prototype** members — methods and accessors (getters\u002F\nsetters) — but **not** instance fields (those live on `this`, not the prototype).\n\n```js\nclass A {\n  get label() { return 'A' }\n  x = 1                       \u002F\u002F instance field\n}\nclass B extends A {\n  get label() { return super.label + 'B' }  \u002F\u002F 'AB'\n  getX() { return super.x }                   \u002F\u002F undefined (field, not on proto)\n}\n```\n\nSince `super` looks up the parent prototype, it sees inherited methods\u002Faccessors\nbut not own instance fields, which belong to the instance.\n",{"id":1736,"difficulty":84,"q":1737,"a":1738},"constructor-order","What is the order of initialization in a class hierarchy?","For `new Child()`: the chain of `super()` calls runs **top-down** (parent\nconstructor first), and **fields** initialize right after that level's\n`super()` returns, before the rest of that constructor's body.\n\n```js\nclass A { constructor() { console.log('A ctor'); this.init() } init(){} }\nclass B extends A {\n  x = (console.log('B field'), 1)\n  constructor() { super(); console.log('B ctor') }\n}\n\u002F\u002F new B(): \"A ctor\" -> \"B field\" -> \"B ctor\"\n```\n\nA classic trap: a parent constructor calling an overridable method runs the\nchild override **before** the child's fields are initialized — so the override\nmay see `undefined`.\n",{"id":1740,"difficulty":63,"q":1741,"a":1742},"instanceof-hierarchy","How does instanceof behave across an inheritance hierarchy?","`instanceof` is true for the class and all its ancestors, since each ancestor's\n`prototype` is in the chain.\n\n```js\nclass A {}\nclass B extends A {}\nclass C extends B {}\nconst c = new C()\nc instanceof C   \u002F\u002F true\nc instanceof B   \u002F\u002F true\nc instanceof A   \u002F\u002F true\n```\n\nSo `instanceof` answers \"is-a (or descends-from)\". To check the *exact* class,\ncompare `obj.constructor === C` or `Object.getPrototypeOf(obj) === C.prototype`.\n",{"id":1744,"difficulty":84,"q":1745,"a":1746},"mixin-with-extends","How do you achieve multiple inheritance with classes?","JavaScript allows only single `extends`, so you simulate multiple inheritance\nwith **mixins** — functions that take a base class and return an extended one,\nchained together.\n\n```js\nconst Serializable = (B) => class extends B { serialize() {} }\nconst Comparable  = (B) => class extends B { compareTo() {} }\n\nclass Model extends Serializable(Comparable(Object)) {}\n```\n\nEach mixin wraps the previous class, building a linear chain that combines\nbehaviors. This is the standard pattern for \"implementing multiple interfaces\"\nof behavior in JS.\n",{"id":1748,"difficulty":84,"q":1749,"a":1750},"super-this-binding","What is this when calling super.method()?","`this` stays the **current instance** — `super.method()` runs the parent's\nmethod but with the child instance as `this`, so it operates on the child's data.\n\n```js\nclass A { describe() { return this.constructor.name } }\nclass B extends A {\n  describe() { return super.describe() }   \u002F\u002F parent method, child `this`\n}\nnew B().describe()   \u002F\u002F 'B' — this.constructor is B\n```\n\n`super` changes *which method* runs, not the receiver. That's why an inherited\nmethod can still see the subclass's overridden properties and constructor.\n",{"id":1752,"difficulty":84,"q":1753,"a":1754},"overriding-getter","How do you override a getter or setter in a subclass?","Redefine the accessor in the subclass. Note that defining only a getter (or only\na setter) in the child can **hide** the inherited pair, so redefine both if\nneeded.\n\n```js\nclass A {\n  get value() { return 1 }\n  set value(v) {}\n}\nclass B extends A {\n  get value() { return super.value + 1 }   \u002F\u002F extend\n  \u002F\u002F if you define only the getter, the inherited setter is shadowed away\n}\n```\n\nAccessors are properties, so overriding one member of a get\u002Fset pair replaces\nthe whole property descriptor — define both in the child to keep both behaviors.\n",{"id":1756,"difficulty":63,"q":1757,"a":1758},"protected-convention","Does JavaScript have protected members?","No `protected` keyword. The conventions are: `_underscore` (a hint that it's\n\"internal,\" not enforced) or `#private` (truly private, but **not** accessible\nto subclasses).\n\n```js\nclass Base {\n  _internal = 1   \u002F\u002F convention: subclasses may use, but not enforced\n  #secret = 2     \u002F\u002F private — subclasses CANNOT access this\n}\n```\n\n`#private` is stricter than protected (even subclasses can't see it). For\nsubclass-accessible-but-not-public members, the `_` convention is all JS offers.\n",{"id":1760,"difficulty":84,"q":1761,"a":1762},"calling-overridden-from-parent","Can a parent method call a method overridden by the child?","Yes — method dispatch is dynamic, so a parent method calling `this.foo()` runs\nthe **child's** override if there is one. This is the template-method pattern.\n\n```js\nclass Base {\n  process() { return this.transform(this.read()) }  \u002F\u002F calls overrides\n  read() { return 'data' }\n  transform(x) { return x }\n}\nclass Json extends Base {\n  transform(x) { return JSON.parse(x) }   \u002F\u002F parent's process() uses this\n}\n```\n\nBecause `this` is the actual instance, the inherited `process()` polymorphically\ninvokes the subclass's `transform` — powerful, but watch the constructor-order\ntrap.\n",{"id":1764,"difficulty":84,"q":1765,"a":1766},"super-not-in-arrow","How does super behave inside an arrow function in a method?","An arrow function lexically captures `super` from its enclosing method, so\n`super.x` works inside an arrow defined within a method.\n\n```js\nclass B extends A {\n  greet() {\n    const fn = () => super.greet()   \u002F\u002F super captured lexically\n    return fn()\n  }\n}\n```\n\nLike `this`, `super` is lexical in arrows — it binds to where the arrow is\nwritten. A regular nested function, by contrast, has no `super` binding.\n",{"id":1768,"difficulty":84,"q":1769,"a":1770},"extends-null","What does extends null do?","`class C extends null` creates a class whose instances do **not** inherit from\n`Object.prototype` — like `Object.create(null)` but as a class. It's an edge case\nand tricky (you must manually handle the prototype in the constructor).\n\n```js\nclass NullProto extends null {\n  constructor() { return Object.create(new.target.prototype) }\n}\n```\n\nInstances lack `toString`, `hasOwnProperty`, etc. It's rarely used — mainly for\ncreating prototype-less objects via class syntax. Most code never needs it.\n",{"id":1772,"difficulty":63,"q":1773,"a":1774},"refactor-function-to-class","What changes when refactoring a constructor function to a class?","Mostly cosmetic, but watch the behavioral differences: classes **must** be called\nwith `new`, are **not usable before declaration** (TDZ), run in **strict mode**,\nand have **non-enumerable** methods.\n\n```js\n\u002F\u002F these worked with the function but not the class:\nconst f = MyFunc()        \u002F\u002F -> class: TypeError (needs new)\nnew MyClassUsedAbove()    \u002F\u002F -> ReferenceError (TDZ) if used before declaration\n```\n\nSo code that relied on calling without `new`, hoisting, or sloppy-mode behavior\ncan break. The upside is those were usually bugs the class now catches.\n",{"id":1776,"difficulty":63,"q":1777,"a":1778},"super-multiple-levels","How does super work across multiple inheritance levels?","Each class's `super` refers to its **immediate** parent, so a method can be\nextended at each level and chained via `super`.\n\n```js\nclass A { greet() { return 'A' } }\nclass B extends A { greet() { return super.greet() + 'B' } }\nclass C extends B { greet() { return super.greet() + 'C' } }\nnew C().greet()   \u002F\u002F 'ABC'\n```\n\n`super` is statically bound to the class where the method is defined (its\n`[[HomeObject]]`), not the runtime instance — so multi-level chains resolve\ncorrectly even with overrides.\n",{"id":1780,"difficulty":63,"q":1781,"a":1782},"composition-via-fields","How do you compose behavior by holding instances (has-a)?","Instead of inheriting, a class can **hold** another object and delegate to it —\ncomposition over inheritance.\n\n```js\nclass Engine { start() { return 'vroom' } }\nclass Car {\n  #engine = new Engine()              \u002F\u002F has-a Engine\n  start() { return this.#engine.start() }  \u002F\u002F delegate\n}\n```\n\nThis avoids tight coupling to a base class and lets you swap the held object.\nMany designs that look like inheritance are cleaner as composition with\ndelegation.\n",{"description":61},"JavaScript class inheritance interview questions — extends, super, overriding, constructor chaining, polymorphism and extending built-ins.","javascript\u002Fclasses\u002Fclass-inheritance","Inheritance with extends & super","Classes & OOP","classes","WkrLqBmf4KArV2-vQoIEAb1a75wOTEM9nf9RxS4CGW4",{"id":1791,"title":1792,"body":1793,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":1797,"navigation":66,"order":12,"path":1798,"questions":1799,"related":207,"seo":1904,"seoDescription":1905,"stem":1906,"subtopic":1907,"topic":1787,"topicSlug":1788,"updated":214,"__hash__":1908},"qa\u002Fjavascript\u002Fclasses\u002Fclass-syntax.md","Class Syntax",{"type":58,"value":1794,"toc":1795},[],{"title":61,"searchDepth":22,"depth":22,"links":1796},[],{},"\u002Fjavascript\u002Fclasses\u002Fclass-syntax",[1800,1804,1808,1812,1816,1820,1824,1828,1832,1836,1840,1844,1848,1852,1856,1860,1864,1868,1872,1876,1880,1884,1888,1892,1896,1900],{"id":1801,"difficulty":71,"q":1802,"a":1803},"what-is-class","What is a class in JavaScript?","A `class` is a template for creating objects — syntactic sugar over constructor\nfunctions and prototypes that gives a cleaner, more familiar OOP syntax.\n\n```js\nclass User {\n  constructor(name) { this.name = name }\n  greet() { return `Hi, ${this.name}` }\n}\nconst u = new User('Ada')\nu.greet()  \u002F\u002F 'Hi, Ada'\n```\n\nUnder the hood, `User` is a function, `greet` lives on `User.prototype`, and\n`new User()` does the usual prototype wiring. Classes add conveniences (strict\nmode, `new`-only, non-enumerable methods) but use the same prototypal machinery.\n",{"id":1805,"difficulty":63,"q":1806,"a":1807},"class-vs-function","How do classes differ from constructor functions?","Classes are functions with extra rules:\n\n- **Must be called with `new`** (throw otherwise).\n- **Always strict mode** inside the body.\n- **Methods are non-enumerable** (won't show in `for...in`).\n- **Not hoisted** for use (temporal dead zone).\n- Built-in `extends`\u002F`super` for inheritance.\n\n```js\nclass C {}\nC()        \u002F\u002F TypeError: Class constructor cannot be invoked without 'new'\nfunction F() {}\nF()        \u002F\u002F fine (no error)\n```\n\nThey're the same prototype mechanism with safer defaults and nicer syntax. The\n`new`-enforcement alone eliminates the classic \"forgot new\" bug.\n",{"id":1809,"difficulty":71,"q":1810,"a":1811},"constructor-method","What is the constructor method?","A special method that runs when an instance is created with `new`, used to\ninitialize instance properties. A class can have **at most one**.\n\n```js\nclass Point {\n  constructor(x, y) {\n    this.x = x\n    this.y = y\n  }\n}\n```\n\nIf you omit it, JavaScript supplies a default empty one (or one that calls\n`super(...args)` in a subclass). The constructor is where per-instance state on\n`this` is set up.\n",{"id":1813,"difficulty":63,"q":1814,"a":1815},"class-methods-prototype","Where do class methods live?","Regular methods are defined on the class's **`prototype`**, so all instances\nshare one copy.\n\n```js\nclass User { greet() {} }\nUser.prototype.greet           \u002F\u002F the method\nconst a = new User(), b = new User()\na.greet === b.greet            \u002F\u002F true — shared\n```\n\nThis is memory-efficient. Class fields and arrow-function fields, by contrast,\nare created **per instance** (on `this`), not on the prototype — an important\ndistinction.\n",{"id":1817,"difficulty":63,"q":1818,"a":1819},"class-fields","What are class fields?","Class fields (public instance fields) let you declare instance properties\ndirectly in the class body, initialized per instance before the constructor body\nruns.\n\n```js\nclass Counter {\n  count = 0               \u002F\u002F instance field\n  step = 1\n  constructor(step) { if (step) this.step = step }\n}\n```\n\nFields are added to each instance (on `this`), not the prototype. They're handy\nfor default values and for arrow-function methods that bind `this`. Each\ninstance gets its own copy.\n",{"id":1821,"difficulty":84,"q":1822,"a":1823},"arrow-class-field","What is the difference between a method and an arrow-function field?","A **method** lives on the prototype (shared) and gets its `this` from the call\nsite. An **arrow-function field** is created per instance and captures `this`\nlexically (bound to the instance) — useful for callbacks.\n\n```js\nclass Btn {\n  label = 'Click'\n  handleA() { return this.label }       \u002F\u002F prototype method — `this` can be lost\n  handleB = () => this.label             \u002F\u002F instance arrow — `this` always bound\n}\nconst b = new Btn()\nconst a = b.handleA; a()   \u002F\u002F this is undefined\nconst c = b.handleB; c()   \u002F\u002F 'Click'\n```\n\nArrow fields cost memory (one per instance) but solve the \"lost `this`\" problem\nfor event handlers without manual `bind`.\n",{"id":1825,"difficulty":63,"q":1826,"a":1827},"class-expression","What is a class expression?","A class defined as an expression (assigned to a variable or passed around),\noptionally named. Mirrors function declarations vs expressions.\n\n```js\nconst User = class { greet() {} }          \u002F\u002F anonymous class expression\nconst Animal = class Named {                \u002F\u002F named (name visible inside only)\n  whoAmI() { return Named.name }\n}\n```\n\nClass expressions are useful for conditionally creating classes, mixins (a\nfunction returning a class), and IIFE-style patterns. Like function expressions,\nthe name in a named class expression is scoped to the class body.\n",{"id":1829,"difficulty":63,"q":1830,"a":1831},"class-hoisting","Are classes hoisted?","Class declarations are hoisted but remain in the **temporal dead zone**, so you\n**can't use them before** their declaration — unlike function declarations.\n\n```js\nnew Foo()   \u002F\u002F ReferenceError: Cannot access 'Foo' before initialization\nclass Foo {}\n```\n\nSo practically, classes behave as \"not hoisted.\" Always declare a class before\ninstantiating or extending it. This is one behavioral difference from converting\na constructor function to a class.\n",{"id":1833,"difficulty":71,"q":1834,"a":1835},"method-shorthand","How do you define different kinds of methods in a class?","The class body supports several method forms:\n\n```js\nclass Example {\n  regular() {}                 \u002F\u002F prototype method\n  static helper() {}           \u002F\u002F on the class itself\n  get value() {}               \u002F\u002F getter\n  set value(v) {}              \u002F\u002F setter\n  async load() {}              \u002F\u002F async method\n  *generate() {}               \u002F\u002F generator method\n  [Symbol.iterator]() {}       \u002F\u002F computed\u002Fsymbol method\n}\n```\n\nAll of these (except fields) go on the prototype (or the class for `static`).\nThe class body is its own syntax — no commas between members, always strict.\n",{"id":1837,"difficulty":63,"q":1838,"a":1839},"getters-setters-class","How do getters and setters work in classes?","`get`\u002F`set` define accessor properties on the prototype that run on read\u002Fwrite,\nso a property can be computed or validated.\n\n```js\nclass Temperature {\n  #celsius = 0\n  get celsius() { return this.#celsius }\n  set celsius(v) {\n    if (typeof v !== 'number') throw new TypeError('number required')\n    this.#celsius = v\n  }\n  get fahrenheit() { return this.#celsius * 1.8 + 32 }\n}\n```\n\nAccessors let you expose a clean property API while validating or deriving\nbehind the scenes. A getter without a setter makes a read-only property.\n",{"id":1841,"difficulty":63,"q":1842,"a":1843},"static-method","What is a static method?","A method on the **class itself**, not on instances — called as `ClassName.method()`.\n`this` inside it is the class.\n\n```js\nclass MathUtil {\n  static square(n) { return n * n }\n}\nMathUtil.square(4)   \u002F\u002F 16\nnew MathUtil().square \u002F\u002F undefined — not on instances\n```\n\nStatics are for utilities and factory methods that don't need instance state\n(`Array.from`, `Object.keys`, `User.fromJSON`). They're inherited by subclasses\nvia the class's own prototype chain.\n",{"id":1845,"difficulty":63,"q":1846,"a":1847},"this-in-class-method","What is this in a class method, and how can it be lost?","In a method called as `instance.method()`, `this` is the instance. Because class\nbodies are strict, extracting the method gives `this === undefined` (a\n`TypeError`), not the global object.\n\n```js\nclass Counter {\n  count = 0\n  inc() { this.count++ }\n}\nconst c = new Counter()\nconst fn = c.inc\nfn()   \u002F\u002F TypeError: Cannot read properties of undefined\n```\n\nFixes: call it on the instance (`() => c.inc()`), `bind` it, or use an\narrow-function field. This is the React class-component `this` problem.\n",{"id":1849,"difficulty":71,"q":1850,"a":1851},"class-vs-object-literal","When should you use a class vs an object literal?","Use a **class** when you need many instances with shared behavior, inheritance,\nor encapsulated state. Use an **object literal** for a single, fixed\nconfiguration or namespace.\n\n```js\nconst config = { apiUrl: '\u002Fapi', timeout: 5000 }   \u002F\u002F one-off -> literal\nclass User { constructor(name) { this.name = name } }  \u002F\u002F many instances -> class\n```\n\nDon't reach for a class just to group functions — a module or plain object is\nsimpler. Classes shine when you're modeling entities that come in multiples.\n",{"id":1853,"difficulty":71,"q":1854,"a":1855},"instanceof-class","How do you check if an object is an instance of a class?","Use `instanceof`, which checks whether the class's `prototype` is in the\nobject's prototype chain (so it sees inheritance).\n\n```js\nclass Animal {}\nclass Dog extends Animal {}\nconst d = new Dog()\nd instanceof Dog     \u002F\u002F true\nd instanceof Animal  \u002F\u002F true (ancestor)\n```\n\nFor cross-realm safety or duck typing, `instanceof` can be unreliable;\n`Symbol.hasInstance` can customize it, and feature checks\n(`typeof obj.bark === 'function'`) are an alternative.\n",{"id":1857,"difficulty":63,"q":1858,"a":1859},"tostring-class","How do you customize how a class instance prints?","Override `toString` (and optionally `Symbol.toPrimitive`) to control string\nconversion in concatenation, template literals, and logging.\n\n```js\nclass Money {\n  constructor(cents) { this.cents = cents }\n  toString() { return `$${(this.cents \u002F 100).toFixed(2)}` }\n}\n`${new Money(150)}`   \u002F\u002F '$1.50'\n```\n\nWithout it, instances stringify to `[object Object]`. For richer debug output in\nNode, you can also implement `[Symbol.for('nodejs.util.inspect.custom')]`.\n",{"id":1861,"difficulty":63,"q":1862,"a":1863},"class-strict-mode","Why are class bodies always in strict mode?","The spec runs all class code in strict mode automatically — no `'use strict'`\nneeded. This surfaces bugs (e.g. `this` is `undefined` in detached methods\ninstead of the global object) and disallows sloppy-mode footguns.\n\n```js\nclass C {\n  m() {\n    undeclared = 1   \u002F\u002F ReferenceError (strict)\n    return this      \u002F\u002F undefined when called without a receiver\n  }\n}\n```\n\nStrict mode is part of what makes classes safer than constructor functions: many\nmistakes throw loudly instead of failing silently.\n",{"id":1865,"difficulty":63,"q":1866,"a":1867},"computed-method-names","Can class method names be computed?","Yes — use `[expression]` for dynamic method names, including well-known symbols.\n\n```js\nconst methodName = 'greet'\nclass User {\n  [methodName]() { return 'hi' }            \u002F\u002F dynamic name\n  [Symbol.iterator]() { \u002F* ... *\u002F }          \u002F\u002F symbol method\n}\nnew User().greet()   \u002F\u002F 'hi'\n```\n\nComputed names enable symbol-keyed methods (making a class iterable, thenable,\netc.) and metaprogramming where method names come from data.\n",{"id":1869,"difficulty":84,"q":1870,"a":1871},"class-field-vs-constructor-assign","What is the difference between a class field and assigning in the constructor?","They're largely equivalent, but timing and inheritance differ. A class field\ninitializes **after `super()`** but **before** the rest of a subclass\nconstructor body; constructor assignment happens wherever you write it.\n\n```js\nclass A {\n  x = 1               \u002F\u002F field\n  constructor() { this.y = 2 }  \u002F\u002F constructor assignment\n}\n```\n\nA subtle gotcha: in a subclass, parent constructor logic runs before the child's\n**fields** are initialized, so a parent method called during construction won't\nsee the child's field values yet.\n",{"id":1873,"difficulty":63,"q":1874,"a":1875},"private-methods-intro","Can classes have private members?","Yes — prefix with `#` for truly private fields and methods, accessible only\ninside the class.\n\n```js\nclass Account {\n  #balance = 0\n  #log(msg) { \u002F* private method *\u002F }\n  deposit(n) { this.#balance += n; this.#log('deposit') }\n  get balance() { return this.#balance }\n}\nnew Account().#balance   \u002F\u002F SyntaxError — private outside class\n```\n\nUnlike the old `_underscore` convention (just a hint), `#private` is enforced by\nthe language. (Covered in depth in the static & private members topic.)\n",{"id":1877,"difficulty":63,"q":1878,"a":1879},"super-call-method","How do you call a parent method from a subclass?","Use `super.method()` inside the subclass — it invokes the parent's version with\nthe current instance as `this`.\n\n```js\nclass Animal { speak() { return 'sound' } }\nclass Dog extends Animal {\n  speak() { return super.speak() + ': woof' }  \u002F\u002F extend, don't replace\n}\nnew Dog().speak()   \u002F\u002F 'sound: woof'\n```\n\n`super` works in any method (not just the constructor) and is the clean\nreplacement for the manual `Parent.prototype.method.call(this)` pattern.\n",{"id":1881,"difficulty":84,"q":1882,"a":1883},"returning-from-class-constructor","Can a class constructor return a value?","Like constructor functions, returning an **object** overrides the instance;\nreturning a primitive is ignored. But in a **derived** class you can only return\nan object or `undefined`.\n\n```js\nclass A { constructor() { return { custom: true } } }\nnew A()   \u002F\u002F { custom: true }\n\nclass B extends A { constructor() { super(); return 5 } } \u002F\u002F 5 ignored -> instance\n```\n\nThis enables caching\u002Fsingleton tricks but is rarely needed and easy to misuse.\nMost constructors should return nothing.\n",{"id":1885,"difficulty":84,"q":1886,"a":1887},"class-toStringTag","How do you change the [object X] tag of a class?","Define a `Symbol.toStringTag` getter to control what\n`Object.prototype.toString.call(instance)` reports.\n\n```js\nclass Collection {\n  get [Symbol.toStringTag]() { return 'Collection' }\n}\nObject.prototype.toString.call(new Collection())\n\u002F\u002F '[object Collection]'\n```\n\nThis affects the default `toString` tag and some debugging output. It's a niche\nfeature, mostly used by built-ins (`Map`, `Promise`) and libraries that want\nmeaningful type tags.\n",{"id":1889,"difficulty":84,"q":1890,"a":1891},"extends-expression","Can you extend an expression, not just a class name?","Yes — `extends` accepts any expression that evaluates to a constructor (or\n`null`). This enables **mixin factories** and dynamic base classes.\n\n```js\nconst Serializable = (Base) => class extends Base {\n  toJSON() { return { ...this } }\n}\nclass Model extends Serializable(Object) {}\n```\n\nBecause `extends \u003Cexpr>` is evaluated, you can compute the superclass — the basis\nof the mixin-via-class-factory pattern. `extends null` creates a class with no\n`Object.prototype` (advanced\u002Frare).\n",{"id":1893,"difficulty":71,"q":1894,"a":1895},"method-chaining-class","How do you enable fluent method chaining in a class?","Return `this` from methods so calls chain on the same instance.\n\n```js\nclass Builder {\n  parts = []\n  add(p) { this.parts.push(p); return this }\n  build() { return this.parts.join('') }\n}\nnew Builder().add('a').add('b').build()   \u002F\u002F 'ab'\n```\n\nReturning the instance is the builder\u002Ffluent pattern, common in query builders\nand configuration APIs. Each method does its work and hands back `this`.\n",{"id":1897,"difficulty":63,"q":1898,"a":1899},"class-pitfall-this-callback","Why do class methods passed as callbacks lose this?","Passing `instance.method` as a callback detaches it from the instance; when the\ncaller invokes it plainly, strict-mode `this` is `undefined`.\n\n```js\nclass Timer {\n  seconds = 0\n  tick() { this.seconds++ }   \u002F\u002F `this` lost if passed directly\n  start() {\n    setInterval(this.tick, 1000)        \u002F\u002F this is undefined\n    setInterval(() => this.tick(), 1000) \u002F\u002F arrow keeps this\n  }\n}\n```\n\nFix with an arrow wrapper, `.bind(this)`, or an arrow-function class field. This\nis the single most common class `this` bug.\n",{"id":1901,"difficulty":63,"q":1902,"a":1903},"when-not-class","When should you avoid classes?","Avoid classes when there's no real instance state or behavior to model — a\nmodule of functions or a plain object is simpler and more idiomatic in JS.\n\n```js\n\u002F\u002F class just to namespace stateless functions\nclass StringUtils { static reverse(s) { return [...s].reverse().join('') } }\n\n\u002F\u002F plain functions \u002F module\nexport const reverse = (s) => [...s].reverse().join('')\n```\n\nFunctional and composition-based code often reads better in JavaScript than\nclass hierarchies. Use classes for genuine entities with state + behavior +\n(sometimes) inheritance — not as a default container.\n",{"description":61},"JavaScript class interview questions — class syntax, constructors, methods, fields, classes vs constructor functions, hoisting and common gotchas.","javascript\u002Fclasses\u002Fclass-syntax","Class Syntax & Methods","nrOdp4po-2N3gRIW5xxIV4MrZLoT1Apgk_BkUHFZq_0",{"id":1910,"title":1911,"body":1912,"description":61,"difficulty":84,"extension":64,"framework":11,"frameworkSlug":9,"meta":1916,"navigation":66,"order":40,"path":1917,"questions":1918,"related":207,"seo":2011,"seoDescription":2012,"stem":2013,"subtopic":2014,"topic":1787,"topicSlug":1788,"updated":214,"__hash__":2015},"qa\u002Fjavascript\u002Fclasses\u002Fmixins-composition.md","Mixins Composition",{"type":58,"value":1913,"toc":1914},[],{"title":61,"searchDepth":22,"depth":22,"links":1915},[],{},"\u002Fjavascript\u002Fclasses\u002Fmixins-composition",[1919,1923,1927,1931,1935,1939,1943,1947,1951,1955,1959,1963,1967,1971,1975,1979,1983,1987,1991,1995,1999,2003,2007],{"id":1920,"difficulty":63,"q":1921,"a":1922},"what-is-mixin","What is a mixin?","A mixin is a reusable bundle of methods that can be added to multiple classes or\nobjects without using inheritance — a way to share behavior across unrelated\ntypes.\n\n```js\nconst serializable = {\n  serialize() { return JSON.stringify(this) },\n}\nclass User {}\nObject.assign(User.prototype, serializable)  \u002F\u002F mix in\nnew User().serialize()\n```\n\nMixins solve \"I need this capability in several classes that don't share a common\nparent.\" They're JavaScript's answer to multiple inheritance and interface-style\nsharing.\n",{"id":1924,"difficulty":63,"q":1925,"a":1926},"object-assign-mixin","How do you implement a mixin with Object.assign?","Copy the mixin's methods onto a class's prototype (shared) or onto an instance.\n\n```js\nconst canFly = { fly() { return `${this.name} flies` } }\nconst canSwim = { swim() { return `${this.name} swims` } }\n\nclass Duck { constructor(name) { this.name = name } }\nObject.assign(Duck.prototype, canFly, canSwim)\n\nconst d = new Duck('Donald')\nd.fly(); d.swim()\n```\n\n`Object.assign(Class.prototype, ...mixins)` adds the methods once for all\ninstances. The mixin methods use `this`, so they operate on whatever object they\nend up on.\n",{"id":1928,"difficulty":84,"q":1929,"a":1930},"mixin-factory","What is a mixin factory (subclass factory)?","A function that takes a base class and returns a new class extending it with\nadded behavior — composable via nesting.\n\n```js\nconst Timestamped = (Base) => class extends Base {\n  constructor(...args) { super(...args); this.createdAt = Date.now() }\n}\nconst Serializable = (Base) => class extends Base {\n  toJSON() { return { ...this } }\n}\nclass Model extends Timestamped(Serializable(Object)) {}\n```\n\nEach factory wraps the previous class, building a linear chain that combines\nfeatures — the idiomatic modern mixin pattern, since it works with `super` and\n`extends`.\n",{"id":1932,"difficulty":63,"q":1933,"a":1934},"composition-over-inheritance","What does \"favor composition over inheritance\" mean?","Build objects by **combining small, focused pieces** (functions, mixins, held\nobjects) rather than inheriting from a deep class hierarchy — more flexible and\nless coupled.\n\n```js\n\u002F\u002F inheritance: rigid hierarchy\nclass Robot extends Machine {}\n\n\u002F\u002F composition: assemble capabilities\nconst robot = { ...withPower(), ...withMovement(), ...withSensors() }\n```\n\nInheritance locks a type into one hierarchy and suffers the fragile-base-class\nproblem. Composition lets you mix exactly the behaviors needed and swap them\nindependently. It's a core OO design principle, especially apt in JS.\n",{"id":1936,"difficulty":63,"q":1937,"a":1938},"functional-composition","What is functional composition?","Combining simple functions so the output of one feeds the next, building complex\nbehavior from small reusable parts.\n\n```js\nconst compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x)\nconst pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x)\n\nconst process = pipe(trim, toLowerCase, removeSpaces)\nprocess('  Hello World ')   \u002F\u002F 'helloworld'\n```\n\n`compose` applies right-to-left, `pipe` left-to-right. Function composition is\nthe functional-programming counterpart to object composition — assemble behavior\nfrom tiny, testable units.\n",{"id":1940,"difficulty":63,"q":1941,"a":1942},"duck-typing","What is duck typing?","\"If it walks like a duck and quacks like a duck, it's a duck\" — judging an object\nby whether it has the needed methods\u002Fproperties, not by its class.\n\n```js\nfunction makeItQuack(thing) {\n  if (typeof thing.quack === 'function') return thing.quack()\n  throw new Error('not quackable')\n}\n```\n\nJavaScript leans heavily on duck typing: code checks for capabilities\n(`typeof x.then === 'function'` for thenables) rather than `instanceof`. It pairs\nnaturally with composition and mixins, where behavior matters more than lineage.\n",{"id":1944,"difficulty":63,"q":1945,"a":1946},"mixin-vs-inheritance","When do you use a mixin instead of inheritance?","Use a mixin when a capability is shared by **unrelated** classes, or when a class\nneeds behaviors from **multiple** sources (which single inheritance can't\nprovide).\n\n```js\n\u002F\u002F both need serialization, but aren't otherwise related\nObject.assign(User.prototype, Serializable)\nObject.assign(Invoice.prototype, Serializable)\n```\n\nUse inheritance for a genuine is-a relationship with a single, stable parent. If\nyou find yourself wanting to extend two parents, that's a mixin (or composition)\nsituation.\n",{"id":1948,"difficulty":84,"q":1949,"a":1950},"mixin-conflicts","What happens when two mixins define the same method?","With `Object.assign`, the **last** mixin wins silently — no error, the earlier\nmethod is overwritten.\n\n```js\nconst a = { run() { return 'a' } }\nconst b = { run() { return 'b' } }\nObject.assign(target, a, b)\ntarget.run()   \u002F\u002F 'b' — collision resolved by order, silently\n```\n\nYou must manage conflicts yourself: rename methods, namespace them, or resolve\nexplicitly. This is the trade-off mixins make for flexibility — no automatic\nconflict detection like some languages' traits.\n",{"id":1952,"difficulty":84,"q":1953,"a":1954},"stateful-mixins","How do mixins handle state?","Method-only mixins are simplest. For state, use a **mixin factory** (so it can run\nconstructor logic via `super`) or initialize state in the mixin's methods —\nobject-literal mixins can't easily set up per-instance fields.\n\n```js\nconst Counter = (Base) => class extends Base {\n  #count = 0\n  increment() { return ++this.#count }\n}\nclass Widget extends Counter(Object) {}\n```\n\nThe class-factory form integrates with the constructor chain, so it can declare\nfields and call `super()`. Plain `Object.assign` mixins are best for stateless\nbehavior.\n",{"id":1956,"difficulty":63,"q":1957,"a":1958},"delegation","What is delegation as a composition technique?","Holding another object and **forwarding** calls to it (has-a), instead of\ninheriting — a flexible alternative to subclassing.\n\n```js\nclass Engine { start() { return 'vroom' } }\nclass Car {\n  #engine = new Engine()\n  start() { return this.#engine.start() }   \u002F\u002F delegate\n}\n```\n\nDelegation lets you swap the held object, compose multiple collaborators, and\navoid tight base-class coupling. It's the runtime sibling of prototypal\ndelegation, done explicitly with object fields.\n",{"id":1960,"difficulty":84,"q":1961,"a":1962},"traits","What are \"traits\" and how do they differ from mixins?","Traits are like mixins but with stricter conflict handling — they require explicit\nresolution when methods clash, rather than silently overwriting. JavaScript has no\nbuilt-in traits; libraries emulate them.\n\n```js\n\u002F\u002F emulated trait: throw on conflict instead of silent override\nfunction applyTrait(target, trait) {\n  for (const k of Object.keys(trait)) {\n    if (k in target) throw new Error(`conflict: ${k}`)\n    target[k] = trait[k]\n  }\n}\n```\n\nThe distinction is mostly academic in JS — both share behavior horizontally; the\ndifference is conflict policy. Plain `Object.assign` mixins are the common\nreality.\n",{"id":1964,"difficulty":63,"q":1965,"a":1966},"react-hooks-composition","How is composition used outside of classes?","Modern JS increasingly composes **functions** rather than objects — e.g. React\nhooks, higher-order functions, and middleware pipelines all build behavior by\ncombining functions.\n\n```js\n\u002F\u002F composing custom hooks (function composition of behavior)\nfunction useUser(id) {\n  const data = useFetch(`\u002Fusers\u002F${id}`)\n  const auth = useAuth()\n  return { ...data, isOwner: auth.id === id }\n}\n```\n\nThe trend in JS is away from class hierarchies toward composing small functions\nand objects. Understanding composition matters even if you rarely write classes.\n",{"id":1968,"difficulty":84,"q":1969,"a":1970},"mixin-super","Can a mixin call the base class's method?","Yes — if it's a **class-factory mixin**, it can use `super.method()` to call the\nwrapped base class, enabling cooperative behavior.\n\n```js\nconst Loud = (Base) => class extends Base {\n  speak() { return super.speak().toUpperCase() }  \u002F\u002F augments base\n}\nclass Animal { speak() { return 'hi' } }\nclass Dog extends Loud(Animal) {}\nnew Dog().speak()   \u002F\u002F 'HI'\n```\n\nObject-literal mixins can't use `super` (no base class), but class-factory mixins\nsit in the prototype chain, so `super` works — letting mixins decorate inherited\nmethods.\n",{"id":1972,"difficulty":63,"q":1973,"a":1974},"object-composition-pattern","How do you compose objects with factory functions?","Build an object by spreading capability objects into it — each capability is a\nsmall factory that closes over shared state.\n\n```js\nconst hasName = (name) => ({ getName: () => name })\nconst canGreet = (self) => ({ greet: () => `Hi, ${self.getName()}` })\n\nfunction createPerson(name) {\n  const self = { ...hasName(name) }\n  return { ...self, ...canGreet(self) }\n}\n```\n\nThis factory-composition style avoids `class`\u002F`this`\u002F`new` entirely, assembling\nbehavior from functions. It's popular in functional-leaning JS codebases.\n",{"id":1976,"difficulty":63,"q":1977,"a":1978},"interface-segregation-js","How do mixins relate to interfaces?","JavaScript has no `interface` keyword, but mixins act like **implementable\ninterfaces of behavior** — a class can \"implement\" several capabilities by mixing\nthem in, similar to implementing multiple interfaces.\n\n```js\nclass FileLogger extends Loggable(Serializable(Object)) {}\n\u002F\u002F \"implements\" Loggable and Serializable behaviors\n```\n\nWhere a typed language declares `implements A, B`, JS mixes the actual behavior\nin. (TypeScript adds real `interface`\u002F`implements` on top for type checking.)\n",{"id":1980,"difficulty":63,"q":1981,"a":1982},"avoid-deep-hierarchy","What problems come from deep inheritance hierarchies?","Deep hierarchies cause the **fragile base class** problem (a base change breaks\nfar-off subclasses), tight coupling, rigidity (a type is stuck in one tree), and\n\"yo-yo\" debugging across many levels.\n\n```js\n\u002F\u002F hard to change Animal without risking Dog, Puppy, ServiceDog, ...\nclass ServiceDog extends Puppy extends Dog extends Animal {}\n```\n\nFlatten with composition: give objects the behaviors they need from small mixins\u002F\ncollaborators instead of inheriting a long chain. Two or three levels is usually\na practical ceiling.\n",{"id":1984,"difficulty":63,"q":1985,"a":1986},"composition-testing","Why is composition easier to test than inheritance?","Composed pieces are small, independent units you can test in isolation and swap\nwith fakes. Inheritance ties behavior to a hierarchy, so testing a subclass drags\nin the whole base.\n\n```js\nclass Order {\n  constructor(payment) { this.payment = payment }   \u002F\u002F injected collaborator\n  checkout() { return this.payment.charge() }\n}\nnew Order({ charge: () => 'mock' }).checkout()   \u002F\u002F easy to fake\n```\n\nDependency injection + composition lets you substitute collaborators in tests.\nThat testability is a major reason \"composition over inheritance\" holds.\n",{"id":1988,"difficulty":63,"q":1989,"a":1990},"assign-vs-spread-mixin","What is the difference between mixing into the prototype vs each instance?","Mixing into the **prototype** (`Object.assign(Class.prototype, mixin)`) shares one\ncopy across all instances. Mixing into each **instance** (in the constructor)\ngives every object its own copy — more memory, but allows per-instance\ncustomization.\n\n```js\nObject.assign(User.prototype, mixin)   \u002F\u002F shared (efficient)\n\u002F\u002F vs\nclass User { constructor() { Object.assign(this, mixin) } }  \u002F\u002F per-instance\n```\n\nPrefer prototype mixing for shared stateless behavior. Per-instance mixing is for\nwhen each object needs independently modifiable methods\u002Fstate.\n",{"id":1992,"difficulty":84,"q":1993,"a":1994},"higher-order-component","How does the decorator\u002Fwrapper pattern relate to composition?","A decorator wraps an object\u002Ffunction to add behavior while preserving the\ninterface — composition by **layering**.\n\n```js\nconst withLogging = (fn) => (...args) => {\n  console.log('calling', fn.name, args)\n  return fn(...args)\n}\nconst loggedFetch = withLogging(fetch)\n```\n\nHigher-order functions (and React HOCs) wrap to extend behavior without modifying\nthe original — the same compositional idea as class-factory mixins, applied to\nfunctions\u002Fcomponents.\n",{"id":1996,"difficulty":84,"q":1997,"a":1998},"when-mixin-bad","What are the downsides of mixins?","Mixins can cause **name collisions** (silent overrides), make it unclear where a\nmethod came from (implicit behavior), create hidden coupling between mixin and\nhost, and complicate `this` reasoning.\n\n```js\nObject.assign(C.prototype, a, b, c)  \u002F\u002F which mixin defined `process`? unclear\n```\n\nUse them sparingly and namespace methods to reduce clashes. Often plain\ncomposition\u002Fdelegation (an explicit collaborator object) is clearer than mixing\nmethods into a prototype.\n",{"id":2000,"difficulty":63,"q":2001,"a":2002},"capability-pattern","How do you give an object only the capabilities it needs?","Compose exactly the behaviors required, rather than inheriting a broad base that\nincludes extras.\n\n```js\nconst readable = (store) => ({ read: (k) => store[k] })\nconst writable = (store) => ({ write: (k, v) => { store[k] = v } })\n\nconst readOnly = { ...readable(data) }              \u002F\u002F only read\nconst readWrite = { ...readable(data), ...writable(data) }\n```\n\nThis \"interface segregation\" via composition keeps objects minimal and intention-\nrevealing — you grant precisely the capabilities needed, avoiding the bloat of a\ndo-everything base class.\n",{"id":2004,"difficulty":84,"q":2005,"a":2006},"this-in-mixin","How does this behave inside a mixin method?","A mixin method's `this` is whatever object it's called on (the host instance), so\nit operates on the host's data — that's what makes mixins reusable across types.\n\n```js\nconst describable = {\n  describe() { return `${this.type}: ${this.name}` }\n}\nObject.assign(Product.prototype, describable)\nnew Product().describe()   \u002F\u002F uses the Product's this.type \u002F this.name\n```\n\nThe mixin doesn't care which class it's in — it just uses `this`. Avoid arrow\nfunctions in object-literal mixins (they'd capture the wrong `this`); use regular\nmethod shorthand.\n",{"id":2008,"difficulty":63,"q":2009,"a":2010},"prefer-composition-summary","How do you decide between inheritance, mixins, and composition?","A practical rule of thumb:\n\n- **Inheritance** — a true, stable **is-a** with one parent (`Circle` is a\n  `Shape`).\n- **Mixins** — a **capability** shared by unrelated classes\n  (`Serializable`, `Comparable`).\n- **Composition\u002Fdelegation** — a **has-a** relationship or swappable collaborator\n  (`Car` has an `Engine`).\n\n```js\nclass Circle extends Shape {}                 \u002F\u002F is-a\nObject.assign(Circle.prototype, Serializable) \u002F\u002F capability\nclass Car { #engine = new Engine() }          \u002F\u002F has-a\n```\n\nDefault to composition; reach for inheritance only for genuine is-a hierarchies,\nand mixins for cross-cutting behaviors.\n",{"description":61},"JavaScript mixins and composition interview questions — sharing behavior without inheritance, mixin factories, composition over inheritance, and duck typing.","javascript\u002Fclasses\u002Fmixins-composition","Mixins & Composition","aHIXUIyhSVDUwHvZ-v5yI9JeKd24BUHXfIhRZezvWQU",{"id":2017,"title":2018,"body":2019,"description":61,"difficulty":84,"extension":64,"framework":11,"frameworkSlug":9,"meta":2023,"navigation":66,"order":31,"path":2024,"questions":2025,"related":207,"seo":2122,"seoDescription":2123,"stem":2124,"subtopic":2125,"topic":1787,"topicSlug":1788,"updated":214,"__hash__":2126},"qa\u002Fjavascript\u002Fclasses\u002Fstatic-private.md","Static Private",{"type":58,"value":2020,"toc":2021},[],{"title":61,"searchDepth":22,"depth":22,"links":2022},[],{},"\u002Fjavascript\u002Fclasses\u002Fstatic-private",[2026,2030,2034,2038,2042,2046,2050,2054,2058,2062,2066,2070,2074,2078,2082,2086,2090,2094,2098,2102,2106,2110,2114,2118],{"id":2027,"difficulty":63,"q":2028,"a":2029},"static-members","What are static members?","Members (methods or fields) that belong to the **class itself**, not to\ninstances. Accessed as `ClassName.member`.\n\n```js\nclass MathUtil {\n  static PI = 3.14159\n  static square(n) { return n * n }\n}\nMathUtil.PI          \u002F\u002F 3.14159\nMathUtil.square(4)   \u002F\u002F 16\nnew MathUtil().square \u002F\u002F undefined — not on instances\n```\n\nStatics suit utilities and class-level data that don't depend on a particular\ninstance. They're shared (one copy on the class) and inherited by subclasses.\n",{"id":2031,"difficulty":63,"q":2032,"a":2033},"static-methods-use","When do you use a static method?","For operations related to the class but not to a specific instance — most\ncommonly **factory methods** and utilities.\n\n```js\nclass User {\n  constructor(name) { this.name = name }\n  static fromJSON(json) { return new User(JSON.parse(json).name) }\n  static compare(a, b) { return a.name.localeCompare(b.name) }\n}\nconst u = User.fromJSON('{\"name\":\"Ada\"}')\n```\n\nStatic factory methods (`User.fromJSON`, `Array.from`, `Promise.resolve`) are a\ncommon alternative to overloaded constructors. `this` inside a static method is\nthe class.\n",{"id":2035,"difficulty":63,"q":2036,"a":2037},"static-fields","What are static fields?","Class-level properties declared with `static`, shared across all instances and\nthe class — useful for constants, counters, or caches.\n\n```js\nclass Counter {\n  static count = 0           \u002F\u002F shared\n  constructor() { Counter.count++ }\n}\nnew Counter(); new Counter()\nCounter.count   \u002F\u002F 2\n```\n\nReference them via the class name (`Counter.count`), not `this` (in instance\nmethods `this` is the instance). Static fields are a newer feature; older code\nused `Class.prop = value` after the class.\n",{"id":2039,"difficulty":63,"q":2040,"a":2041},"this-in-static","What is this inside a static method?","The **class itself** — so static methods can call sibling statics and respect\nsubclassing.\n\n```js\nclass Base {\n  static create() { return new this() }   \u002F\u002F `this` is the class\n}\nclass Sub extends Base {}\nBase.create()   \u002F\u002F Base instance\nSub.create()    \u002F\u002F Sub instance — `this` is Sub\n```\n\nBecause `this` is the concrete class, a static factory like `create()` builds an\ninstance of whichever subclass it was called on — useful for polymorphic\nfactories.\n",{"id":2043,"difficulty":63,"q":2044,"a":2045},"private-fields","What are private fields and how do you declare them?","Fields prefixed with `#` are **truly private** — accessible only inside the\nclass body, enforced by the language (not a convention).\n\n```js\nclass Account {\n  #balance = 0\n  deposit(n) { this.#balance += n }\n  get balance() { return this.#balance }\n}\nconst a = new Account()\na.#balance         \u002F\u002F SyntaxError outside the class\na.balance          \u002F\u002F via the getter\n```\n\nUnlike the `_underscore` convention, `#private` can't be accessed or even\ndetected from outside. It's real encapsulation built into the syntax.\n",{"id":2047,"difficulty":63,"q":2048,"a":2049},"private-vs-underscore","What is the difference between","`_name` is a **convention** — a hint that a member is internal, but it's still\nfully public and accessible. `#name` is **enforced** privacy — a SyntaxError to\naccess from outside.\n\n```js\nclass C {\n  _soft = 1     \u002F\u002F accessible: c._soft works (just \"please don't\")\n  #hard = 2     \u002F\u002F c.#hard -> SyntaxError\n}\n```\n\nPrefer `#private` for genuine encapsulation. The `_` convention persists in older\ncode and where subclass access is wanted (subclasses can't see `#private`).\n",{"id":2051,"difficulty":63,"q":2052,"a":2053},"private-methods","Can methods be private?","Yes — prefix a method (or getter\u002Fsetter) with `#` to make it callable only from\nwithin the class.\n\n```js\nclass Service {\n  #validate(data) { return !!data }       \u002F\u002F private method\n  get #ready() { return this.#validate(this.data) }  \u002F\u002F private getter\n  submit(data) {\n    this.data = data\n    if (this.#validate(data)) { \u002F* ... *\u002F }\n  }\n}\n```\n\nPrivate methods keep internal helpers off the public API and prevent subclasses\nor callers from depending on them. They live per-class, not on the public\nprototype.\n",{"id":2055,"difficulty":84,"q":2056,"a":2057},"static-private","Can static members be private?","Yes — combine `static` and `#` for private class-level fields and methods,\naccessible only inside the class.\n\n```js\nclass IdGenerator {\n  static #counter = 0\n  static #next() { return ++IdGenerator.#counter }\n  static create() { return { id: IdGenerator.#next() } }\n}\nIdGenerator.#counter   \u002F\u002F SyntaxError\n```\n\nStatic privates are great for internal class state (caches, counters,\nregistries) that shouldn't be touched from outside. Reference them via the class\nname inside the body.\n",{"id":2059,"difficulty":84,"q":2060,"a":2061},"static-block","What is a static initialization block?","A `static { }` block (ES2022) runs once when the class is defined, for complex\nstatic setup that a field initializer can't express — and it can access private\nstatic members.\n\n```js\nclass Config {\n  static settings = {}\n  static {\n    const env = readEnv()             \u002F\u002F run setup logic\n    this.settings = parse(env)\n    this.#secret = deriveSecret(env)  \u002F\u002F can touch private statics\n  }\n  static #secret\n}\n```\n\nIt's the class equivalent of a one-time initializer, useful when static state\nneeds computation, multiple statements, or try\u002Fcatch at definition time.\n",{"id":2063,"difficulty":84,"q":2064,"a":2065},"private-check","How do you check if an object has a private field (brand check)?","Use the `#field in obj` syntax (the \"ergonomic brand check\") — it returns whether\n`obj` has that private field, without throwing.\n\n```js\nclass Stream {\n  #buffer = []\n  static isStream(obj) { return #buffer in obj }\n}\nStream.isStream(new Stream())   \u002F\u002F true\nStream.isStream({})             \u002F\u002F false\n```\n\nThis is the reliable way to detect \"is this a real instance of my class\" — more\nrobust than `instanceof` (which can be spoofed via prototypes). Accessing\n`obj.#buffer` directly on a non-instance would throw, so the `in` form is used.\n",{"id":2067,"difficulty":63,"q":2068,"a":2069},"encapsulation-benefits","Why is encapsulation with private fields valuable?","It hides internal state so callers can't depend on or corrupt it, letting you\nchange the implementation freely and enforce invariants in one place.\n\n```js\nclass Temperature {\n  #celsius = 0\n  set celsius(v) {\n    if (v \u003C -273.15) throw new RangeError('below absolute zero')\n    this.#celsius = v        \u002F\u002F validation can't be bypassed\n  }\n  get celsius() { return this.#celsius }\n}\n```\n\nWith public fields, anyone could set an invalid value directly. Private fields +\naccessors guarantee the validation runs and keep the public surface small and\nstable.\n",{"id":2071,"difficulty":84,"q":2072,"a":2073},"private-inheritance","Are private fields inherited by subclasses?","No — `#private` fields are **not accessible** from subclasses. They belong\nstrictly to the class that declares them.\n\n```js\nclass Base { #secret = 1; getSecret() { return this.#secret } }\nclass Sub extends Base {\n  reveal() { return this.#secret }   \u002F\u002F SyntaxError — not visible\n}\n```\n\nThis is stricter than `protected` in other languages. For state subclasses need,\nuse the `_` convention or expose a protected-style accessor. Private fields are\ntruly class-local.\n",{"id":2075,"difficulty":84,"q":2076,"a":2077},"static-inheritance","Are static members inherited?","Yes — subclasses inherit static methods and fields via the class's own prototype\nchain (`Sub.__proto__ === Base`).\n\n```js\nclass Base { static greet() { return 'hi' } }\nclass Sub extends Base {}\nSub.greet()   \u002F\u002F 'hi' — inherited static\n```\n\nInside an inherited static, `this` is the calling subclass, and `super` reaches\nthe parent's static. Static *fields* are inherited as references — careful, since\na shared static object is shared across the hierarchy.\n",{"id":2079,"difficulty":63,"q":2080,"a":2081},"private-field-must-declare","Do you have to declare private fields before use?","Yes — every private field must be **declared in the class body**. You can't\ncreate one dynamically like a public property.\n\n```js\nclass C {\n  #x = 1            \u002F\u002F must declare\n  m() { this.#y = 2 }   \u002F\u002F SyntaxError — #y not declared\n}\n```\n\nThis is unlike public properties, which can be added anywhere. The requirement\nlets the engine know the full set of private fields at parse time (enabling the\nbrand check and strong encapsulation).\n",{"id":2083,"difficulty":84,"q":2084,"a":2085},"singleton-static","How do you implement a singleton with static members?","Cache the instance in a private static field and expose it via a static getter\nor method, with a guarded\u002Fprivate constructor.\n\n```js\nclass Logger {\n  static #instance\n  static get instance() {\n    return Logger.#instance ??= new Logger()\n  }\n}\nLogger.instance === Logger.instance   \u002F\u002F true\n```\n\nThe private static `#instance` holds the single object; `??=` lazily creates it\nonce. (In JS, a module-level singleton is often simpler, but this is the\nclass-based form.)\n",{"id":2087,"difficulty":63,"q":2088,"a":2089},"static-factory-vs-constructor","Why use static factory methods over constructors?","Static factories can have **descriptive names**, return cached\u002Fsubclass instances,\ndo async work indirectly, and offer multiple \"constructors\" — things a single\nconstructor can't.\n\n```js\nclass Color {\n  constructor(r, g, b) { \u002F* ... *\u002F }\n  static fromHex(hex) { \u002F* parse *\u002F return new Color(\u002F* ... *\u002F) }\n  static fromHSL(h, s, l) { \u002F* convert *\u002F return new Color(\u002F* ... *\u002F) }\n}\n```\n\nNamed factories (`fromHex`, `fromHSL`) read better than overloading one\nconstructor and let you control instance creation (caching, validation). A widely\nused OOP idiom.\n",{"id":2091,"difficulty":63,"q":2092,"a":2093},"private-getter-setter","Can you have private getters and setters?","Yes — `get #name()` \u002F `set #name(v)` define private accessors, usable only inside\nthe class for computed private values.\n\n```js\nclass Box {\n  #w = 0; #h = 0\n  get #area() { return this.#w * this.#h }   \u002F\u002F private computed value\n  report() { return `area: ${this.#area}` }\n}\n```\n\nPrivate accessors are handy for internal derived values you don't want to expose\nor recompute manually. Like all `#` members, they're inaccessible and invisible\noutside the class.\n",{"id":2095,"difficulty":84,"q":2096,"a":2097},"weakmap-privacy","How was privacy done before","With closures (per-instance functions) or a module-scoped **`WeakMap`** keyed by\ninstance — both hide data from outside the class.\n\n```js\nconst _balance = new WeakMap()\nclass Account {\n  constructor() { _balance.set(this, 0) }\n  deposit(n) { _balance.set(this, _balance.get(this) + n) }\n  get balance() { return _balance.get(this) }\n}\n```\n\nThe `WeakMap` lives in module scope, so only the class's methods can read it, and\nentries are garbage-collected with the instance. `#private` fields now do this\nnatively and more cleanly.\n",{"id":2099,"difficulty":63,"q":2100,"a":2101},"static-vs-module","When should you use a static method vs a module function?","Use a **static method** when the function is conceptually tied to the class\n(factories, class-specific helpers, polymorphic via `this`). Use a **plain module\nfunction** for standalone utilities not bound to a class.\n\n```js\n\u002F\u002F tied to the class -> static\nclass Vector { static add(a, b) { \u002F* ... *\u002F } }\n\u002F\u002F generic utility -> module function\nexport function clamp(n, lo, hi) { \u002F* ... *\u002F }\n```\n\nDon't create a class full of only static methods just to namespace functions — a\nmodule is the idiomatic JS namespace. Statics belong with classes that also have\ninstances.\n",{"id":2103,"difficulty":63,"q":2104,"a":2105},"private-method-vs-closure","What is the advantage of a private method over a closure helper?","A `#private` method lives on the class **once** (shared), whereas a closure helper\ndefined per instance (or inside the constructor) is duplicated per object. Private\nmethods give encapsulation **and** memory efficiency.\n\n```js\nclass Service {\n  #parse(x) { \u002F* shared across instances *\u002F }   \u002F\u002F one definition\n}\n\u002F\u002F vs a per-instance closure in the constructor (one function per object)\n```\n\nSo `#private` methods are usually better than closure-based privacy for classes:\nsame hiding, no per-instance function cost.\n",{"id":2107,"difficulty":63,"q":2108,"a":2109},"enum-pattern","How do you create enum-like constants with static members?","Use static fields (often on a frozen class) to model a fixed set of named\nconstants.\n\n```js\nclass Direction {\n  static North = new Direction('N')\n  static South = new Direction('S')\n  constructor(code) { this.code = code }\n}\nObject.freeze(Direction)\nDirection.North.code   \u002F\u002F 'N'\n```\n\nJavaScript has no native `enum`, so frozen static instances (or a frozen plain\nobject `Object.freeze({ North: 'N', ... })`) are the common patterns for\nenumerations.\n",{"id":2111,"difficulty":84,"q":2112,"a":2113},"static-this-pitfall","What is a common pitfall referencing static fields?","Inside an **instance** method, `this` is the instance, so `this.staticField` is\n`undefined` — you must use the class name (or `this.constructor`).\n\n```js\nclass C {\n  static MAX = 10\n  check(n) {\n    return n \u003C this.MAX            \u002F\u002F undefined — MAX is static\n    \u002F\u002F return n \u003C C.MAX            \u002F\u002F\n    \u002F\u002F return n \u003C this.constructor.MAX  \u002F\u002F subclass-aware\n  }\n}\n```\n\nUse `ClassName.field` for a fixed reference, or `this.constructor.field` if you\nwant subclasses to be able to override the static value.\n",{"id":2115,"difficulty":84,"q":2116,"a":2117},"private-in-operator-guard","Why does accessing a private field on the wrong object throw?","Private fields are \"branded\" to their class. Reading `obj.#field` on an object\nthat isn't an instance throws a `TypeError`, which protects encapsulation but\nmeans you should guard with `#field in obj` first.\n\n```js\nclass A { #x = 1; static read(o) { return #x in o ? o.#x : null } }\nA.read(new A())   \u002F\u002F 1\nA.read({})        \u002F\u002F null (guarded; direct o.#x would throw)\n```\n\nThe throw-on-mismatch behavior is what makes `#field in obj` the safe brand\ncheck, and prevents one class's private accessor from working on foreign objects.\n",{"id":2119,"difficulty":63,"q":2120,"a":2121},"freeze-class","How do you make a class's static configuration immutable?","Freeze the class (and\u002For its static objects) so static fields can't be reassigned\nafter definition.\n\n```js\nclass Config {\n  static API = '\u002Fv1'\n  static TIMEOUT = 5000\n}\nObject.freeze(Config)\nConfig.API = '\u002Fv2'   \u002F\u002F ignored (throws in strict mode)\n```\n\n`Object.freeze(Config)` locks top-level static props; nested static objects need\ntheir own freeze (it's shallow). A `static {}` block plus `Object.freeze` is a\nclean way to set up immutable class-level config.\n",{"description":61},"JavaScript static and private class member interview questions — static methods and fields, private fields and methods, static blocks, and encapsulation patterns.","javascript\u002Fclasses\u002Fstatic-private","Static & Private Members","J6BpWyoml9KkWfwfDsQHBLHqJm6SUDbQqoQYjj8Gipc",{"id":2128,"title":2129,"body":2130,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":2134,"navigation":66,"order":12,"path":2135,"questions":2136,"related":207,"seo":2273,"seoDescription":2274,"stem":2275,"subtopic":2129,"topic":2276,"topicSlug":2277,"updated":1525,"__hash__":2278},"qa\u002Fjavascript\u002Ffunctions\u002Fclosures.md","Closures",{"type":58,"value":2131,"toc":2132},[],{"title":61,"searchDepth":22,"depth":22,"links":2133},[],{},"\u002Fjavascript\u002Ffunctions\u002Fclosures",[2137,2141,2145,2149,2153,2157,2161,2165,2169,2173,2177,2181,2185,2189,2193,2197,2201,2205,2209,2213,2217,2221,2225,2229,2233,2237,2241,2245,2249,2253,2257,2261,2265,2269],{"id":2138,"difficulty":63,"q":2139,"a":2140},"what-is-closure","What is a closure?","A closure is a function bundled together with a **reference to the lexical\nscope in which it was created**. Because of that bundle, the inner function\nkeeps access to its outer variables **even after the outer function has\nreturned** and that outer call's scope would otherwise be gone.\n\n```js\nfunction counter() {\n  let count = 0           \u002F\u002F lives in counter's scope\n  return () => ++count    \u002F\u002F this arrow closes over `count`\n}\n\nconst next = counter()    \u002F\u002F counter() has returned...\nnext() \u002F\u002F 1               \u002F\u002F ...yet `count` is still alive and remembered\nnext() \u002F\u002F 2\n```\n\nThe key insight interviewers want: the closure captures the **variable itself\n(the binding), not a copy of its value**. So `count` is genuinely shared and\nmutable across calls — each `next()` sees and updates the same `count`. Every\nfunction in JavaScript is technically a closure; it only *matters* when the\nfunction outlives the scope it captured.\n",{"id":2142,"difficulty":63,"q":2143,"a":2144},"closure-use","What are practical uses of closures?","Closures are everywhere in real JavaScript, usually to **remember state\nbetween calls** without a global variable or a class:\n\n- **Data privacy \u002F encapsulation** — the module pattern, private counters,\n  anything you don't want callers to touch directly.\n- **Function factories & currying \u002F partial application** — pre-fill some\n  arguments and return a specialized function.\n- **Callbacks & event handlers** — a handler remembers the data it was set up\n  with.\n- **Memoization** — keep a private cache between invocations.\n\n```js\nfunction memoize(fn) {\n  const cache = new Map()        \u002F\u002F private, persists across calls\n  return arg => {\n    if (cache.has(arg)) return cache.get(arg)\n    const result = fn(arg)\n    cache.set(arg, result)\n    return result\n  }\n}\n```\n",{"id":2146,"difficulty":84,"q":2147,"a":2148},"closure-memory","Can closures cause memory leaks?","Yes. A closure keeps its captured scope alive for as long as the closure\nitself is reachable. If that closure outlives its usefulness while holding\nreferences to **large objects or detached DOM nodes**, the garbage collector\ncan't reclaim them — a leak.\n\n```js\nfunction attach() {\n  const huge = new Array(1_000_000).fill('🐘')\n  document.getElementById('btn').addEventListener('click', () => {\n    \u002F\u002F this handler closes over `huge`, pinning it in memory forever\n    console.log(huge.length)\n  })\n}\n```\n\nMitigations: remove event listeners when you're done\n(`removeEventListener`), null out references you no longer need, avoid\ncapturing more than necessary, and consider `WeakMap`\u002F`WeakRef` for caches so\nentries can be collected when nothing else references the key.\n",{"id":2150,"difficulty":84,"q":2151,"a":2152},"closure-loop","How do closures explain the classic for-loop var bug?","With `var`, the loop variable is **function-scoped**, so there's a *single*\nbinding shared by every iteration. By the time the deferred callbacks run, the\nloop has finished and they all read that one binding's **final value**. `let`\nis **block-scoped** and creates a **fresh binding per iteration**, so each\ncallback closes over its own copy.\n\n```js\n\u002F\u002F all share one `i`, which is 3 when the timeouts fire\nfor (var i = 0; i \u003C 3; i++) setTimeout(() => console.log(i)) \u002F\u002F 3 3 3\n\n\u002F\u002F a new `i` per iteration\nfor (let i = 0; i \u003C 3; i++) setTimeout(() => console.log(i)) \u002F\u002F 0 1 2\n```\n\nBefore `let` existed, the fix was to create a new scope manually with an IIFE:\n`(j => setTimeout(() => console.log(j)))(i)`. This question is really testing\nwhether you understand *binding vs value* capture.\n",{"id":2154,"difficulty":63,"q":2155,"a":2156},"private-vars","How do you create private variables with closures?","Declare variables in an enclosing function scope and return only the functions\nthat should be allowed to touch them. The variables are unreachable from\noutside — there's no reference to them except through the methods you exposed.\n\n```js\nfunction account() {\n  let balance = 0 \u002F\u002F truly private — no outside access\n  return {\n    deposit: n => (balance += n),\n    withdraw: n => (balance -= n),\n    get: () => balance,\n  }\n}\n\nconst a = account()\na.deposit(100)\na.get()       \u002F\u002F 100\na.balance     \u002F\u002F undefined — can't reach the closed-over variable\n```\n\nThis was the canonical way to get encapsulation before JavaScript added\n`#private` class fields, and it still underlies the module pattern.\n",{"id":2158,"difficulty":63,"q":2159,"a":2160},"currying","What is currying and how do closures enable it?","Currying transforms a function that takes **many arguments** into a **chain of\nfunctions that each take one**. Closures make it work: each returned function\n*remembers* the arguments supplied to the earlier ones via its captured scope.\n\n```js\nconst add = a => b => c => a + b + c\nadd(1)(2)(3) \u002F\u002F 6\n\n\u002F\u002F practical: build specialized functions by partially applying\nconst multiply = a => b => a * b\nconst double = multiply(2) \u002F\u002F remembers a = 2\ndouble(10) \u002F\u002F 20\n```\n\nEach inner arrow closes over the parameters of the outer arrows, which is why\n`double` keeps `a = 2` ready for whenever you call it. Useful for\nconfiguration, reusable utilities, and point-free function composition.\n",{"id":2162,"difficulty":71,"q":2163,"a":2164},"iife","What is an IIFE and why was it used?","An **Immediately Invoked Function Expression** is a function that runs the\ninstant it's defined — you wrap it in parentheses to make it an *expression*\nand immediately call it with `()`.\n\n```js\n(function () {\n  const secret = 42 \u002F\u002F scoped to here, not global\n  console.log(secret)\n})()\n```\n\nBefore block scoping (`let`\u002F`const`) and ES modules, the IIFE was the main tool\nfor creating a **private scope**: it kept variables out of the global namespace\n(avoiding name collisions between scripts) and was the backbone of the module\npattern. Today `let`\u002F`const` blocks and real modules cover most of these cases,\nso you see IIFEs less often.\n",{"id":2166,"difficulty":63,"q":2167,"a":2168},"closure-vs-scope","What is the difference between scope and a closure?","They're related but not the same thing:\n\n- **Scope** is a *static* concept: the set of variables accessible at a given\n  location in your code, determined by where things are written (lexical\n  scoping). It exists whether or not any function \"leaves.\"\n- A **closure** is what you get at *runtime* when a function **retains access to\n  its defining scope and carries it along** to be executed somewhere else —\n  after the outer function has returned.\n\n```js\nfunction outer() {\n  const x = 10        \u002F\u002F x is in outer's SCOPE\n  return () => x      \u002F\u002F the returned function + its hold on x = a CLOSURE\n}\nconst fn = outer()    \u002F\u002F outer's scope is gone, but the closure keeps x alive\nfn() \u002F\u002F 10\n```\n\nPut simply: scope defines *what a function can see*; a closure is the function\n*remembering and preserving* that view beyond its original lifetime.\n",{"id":2170,"difficulty":63,"q":2171,"a":2172},"module-pattern","What is the module pattern?","The module pattern uses a closure (classically an IIFE) to create **private\nstate** and expose only a public API — the returned object's methods close over\nvariables that are otherwise inaccessible.\n\n```js\nconst counter = (function () {\n  let count = 0                  \u002F\u002F private\n  return {\n    increment() { count++ },\n    value() { return count },\n  }\n})()\ncounter.increment()\ncounter.value()  \u002F\u002F 1\ncounter.count    \u002F\u002F undefined — truly private\n```\n\nIt was the standard way to organize code and hide internals before ES modules.\nToday `import`\u002F`export` modules serve the same purpose at the file level, but the\npattern still appears for encapsulated singletons.\n",{"id":2174,"difficulty":84,"q":2175,"a":2176},"debounce","How do you implement debounce with a closure?","Debounce delays running a function until input **stops** for a quiet period. A\nclosure holds the pending timer id across calls so each new call can cancel the\nprevious one.\n\n```js\nfunction debounce(fn, delay) {\n  let timer                      \u002F\u002F remembered between calls via closure\n  return function (...args) {\n    clearTimeout(timer)\n    timer = setTimeout(() => fn.apply(this, args), delay)\n  }\n}\nconst onSearch = debounce(query => fetchResults(query), 300)\n```\n\nEach keystroke resets the timer; `fn` runs only 300ms after the **last** call.\nThe private `timer` variable is exactly the kind of persistent state closures\nexist for.\n",{"id":2178,"difficulty":84,"q":2179,"a":2180},"throttle","How does throttle differ from debounce, and how do you implement it?","**Throttle** runs the function **at most once per interval** (regular cadence),\nwhereas **debounce** waits until activity stops. A closure tracks the last run\ntime.\n\n```js\nfunction throttle(fn, limit) {\n  let last = 0\n  return function (...args) {\n    const now = Date.now()\n    if (now - last >= limit) {\n      last = now\n      fn.apply(this, args)\n    }\n  }\n}\nconst onScroll = throttle(() => updatePosition(), 100)\n```\n\nUse **throttle** for continuous events where you want steady updates (scroll,\nresize, mousemove); use **debounce** for \"act after they finish\" (search input,\nautosave).\n",{"id":2182,"difficulty":63,"q":2183,"a":2184},"once","How do you write a once() function?","`once` wraps a function so it runs **only the first time** and returns the cached\nresult thereafter. A closure remembers whether it has been called and the result.\n\n```js\nfunction once(fn) {\n  let called = false, result\n  return function (...args) {\n    if (!called) {\n      called = true\n      result = fn.apply(this, args)\n    }\n    return result\n  }\n}\nconst init = once(() => console.log('init!'))\ninit() \u002F\u002F 'init!'\ninit() \u002F\u002F (nothing — cached)\n```\n\nUseful for one-time initialization, idempotent event handlers, and lazy\nsingletons.\n",{"id":2186,"difficulty":84,"q":2187,"a":2188},"memoize","How do you implement memoization with a closure?","Memoization caches results of expensive pure functions by their arguments. A\nclosure holds a private cache that persists across calls.\n\n```js\nfunction memoize(fn) {\n  const cache = new Map()        \u002F\u002F private, lives between calls\n  return function (...args) {\n    const key = JSON.stringify(args)\n    if (cache.has(key)) return cache.get(key)\n    const result = fn.apply(this, args)\n    cache.set(key, result)\n    return result\n  }\n}\nconst slowSquare = memoize(n => n * n)\n```\n\nThe cache is invisible to callers — pure encapsulation. Only memoize **pure**\nfunctions, and mind cache growth (a `WeakMap` or LRU cap helps for large key\nspaces).\n",{"id":2190,"difficulty":63,"q":2191,"a":2192},"partial-application","What is partial application and how do closures enable it?","Partial application **fixes some arguments** of a function now, returning a new\nfunction that takes the rest later. The returned function closes over the\npre-supplied arguments.\n\n```js\nfunction partial(fn, ...preset) {\n  return (...rest) => fn(...preset, ...rest) \u002F\u002F closes over `preset`\n}\nconst add = (a, b, c) => a + b + c\nconst add10 = partial(add, 10)\nadd10(20, 30) \u002F\u002F 60\n```\n\nIt differs from currying (which takes args one at a time); partial application\nfixes any number at once. Both rely on closures to remember the bound arguments.\n",{"id":2194,"difficulty":63,"q":2195,"a":2196},"event-handler-state","How do closures help event handlers keep state?","An event handler defined inside a function closes over that function's variables,\nso each handler \"remembers\" the data it was created with — without needing global\nstate or data attributes.\n\n```js\nfunction setupButtons(labels) {\n  labels.forEach((label, i) => {\n    button[i].addEventListener('click', () => {\n      console.log(`clicked ${label} (#${i})`) \u002F\u002F closes over label and i\n    })\n  })\n}\n```\n\nEach handler captures its own `label`\u002F`i`. (Using `let`\u002F`forEach` gives a fresh\nbinding per iteration — the same reason the classic `var` loop bug doesn't\nappear here.)\n",{"id":2198,"difficulty":84,"q":2199,"a":2200},"settimeout-puzzle","What does this setTimeout-in-a-loop snippet print and why?","```js\nfor (var i = 0; i \u003C 3; i++) {\n  setTimeout(() => console.log(i), 100)\n}\n\u002F\u002F 3 3 3\n```\n\nAll three arrow functions close over the **same** `var i` (function-scoped). By\nthe time the timers fire (after the loop completes), `i` is `3`. Fixes:\n\n```js\nfor (let i = 0; i \u003C 3; i++) setTimeout(() => console.log(i), 100) \u002F\u002F 0 1 2\n\u002F\u002F or capture per iteration with an IIFE:\nfor (var i = 0; i \u003C 3; i++) ((j) => setTimeout(() => console.log(j)))(i)\n```\n\nThe lesson: closures capture the **variable binding**, not a snapshot of its\nvalue.\n",{"id":2202,"difficulty":84,"q":2203,"a":2204},"capture-reference","Do closures capture a variable's value or the variable itself?","Closures capture the **variable (binding), not a copy of its value**. So if the\nvariable changes after the closure is created, the closure sees the **new**\nvalue.\n\n```js\nlet x = 1\nconst read = () => x\nx = 99\nread() \u002F\u002F 99 — not 1\n```\n\nThis is why the `var` loop bug happens (all closures share one binding) and why\n`let` fixes it (a fresh binding each iteration). To capture a value snapshot,\ncopy it into a new scope (an IIFE parameter or a `let` in the loop body).\n",{"id":2206,"difficulty":63,"q":2207,"a":2208},"lexical-scoping","What is lexical scoping and how does it relate to closures?","Lexical (static) scoping means a function's accessible variables are determined by\n**where it is written** in the source, not where it's called. Closures are the\nruntime consequence: a function carries its lexical environment with it.\n\n```js\nfunction outer() {\n  const secret = 42\n  function inner() { return secret } \u002F\u002F resolves `secret` by lexical position\n  return inner\n}\nouter()() \u002F\u002F 42 — inner remembers outer's scope wherever it runs\n```\n\nBecause scope is fixed at definition time, you can reason about what a closure can\naccess just by reading the nested structure of the code.\n",{"id":2210,"difficulty":63,"q":2211,"a":2212},"each-call-new-closure","Does each function call create a new closure?","Yes. Every invocation of an outer function creates a **fresh scope**, so any inner\nfunctions returned capture **independent** copies of that scope. Two calls to a\nfactory produce two unrelated states.\n\n```js\nfunction counter() { let n = 0; return () => ++n }\nconst a = counter()\nconst b = counter()\na() \u002F\u002F 1\na() \u002F\u002F 2\nb() \u002F\u002F 1 — separate closure, separate `n`\n```\n\nThis independence is what makes closure-based factories useful: each produced\nobject has its own private state.\n",{"id":2214,"difficulty":71,"q":2215,"a":2216},"function-factory","What is a function factory?","A function factory is a function that **returns customized functions**, each\nclosing over the arguments used to create it. It's a clean way to generate\nspecialized variants.\n\n```js\nfunction makeMultiplier(factor) {\n  return n => n * factor   \u002F\u002F closes over `factor`\n}\nconst double = makeMultiplier(2)\nconst triple = makeMultiplier(3)\ndouble(5) \u002F\u002F 10\ntriple(5) \u002F\u002F 15\n```\n\nEach returned function remembers its own `factor`. Factories built on closures\npower currying, partial application, and configurable utilities.\n",{"id":2218,"difficulty":84,"q":2219,"a":2220},"closures-and-this","Do closures capture this?","No — a closure captures **variables** from its lexical scope, but `this` is **not**\na normal variable for regular functions; it's set by how the function is called.\n**Arrow functions**, however, capture `this` lexically (like a closed-over\nvariable).\n\n```js\nconst obj = {\n  name: 'Ada',\n  regular() { return function () { return this.name } }, \u002F\u002F `this` lost\n  arrow()   { return () => this.name },                  \u002F\u002F `this` captured\n}\nobj.regular()() \u002F\u002F undefined (this is not obj)\nobj.arrow()()   \u002F\u002F 'Ada'  (arrow closes over obj's this)\n```\n\nA common pre-arrow workaround was `const self = this`, which *does* capture `this`\nas an ordinary closed-over variable.\n",{"id":2222,"difficulty":63,"q":2223,"a":2224},"closure-vs-class","How do closures compare to classes for encapsulation?","Both can hide state. **Closures** give true privacy via captured variables, with\na functional feel and no `this`. **Classes** are more familiar, support\ninheritance and (now) `#private` fields, and are more memory-efficient when you\ncreate many instances (methods live once on the prototype).\n\n```js\n\u002F\u002F closure\nconst make = () => { let n = 0; return { inc: () => ++n } }\n\u002F\u002F class\nclass C { #n = 0; inc() { return ++this.#n } }\n```\n\nClosures excel for small factories and one-offs; classes scale better for many\ninstances and rich hierarchies. With `#private` fields, classes now match\nclosures on genuine privacy.\n",{"id":2226,"difficulty":63,"q":2227,"a":2228},"revealing-module","What is the revealing module pattern?","A variation of the module pattern where you define all functions\u002Fvariables\nprivately and **return an object that maps public names to those private\nmembers** — making the public API explicit at the bottom.\n\n```js\nconst calc = (function () {\n  let total = 0\n  function add(n) { total += n }\n  function get() { return total }\n  return { add, get }   \u002F\u002F \"reveal\" only these\n})()\n```\n\nIt improves readability (the exposed surface is listed in one place) and lets you\nrename the public API independently of the private implementation.\n",{"id":2230,"difficulty":84,"q":2231,"a":2232},"generator-vs-closure","How do generators compare to closures for maintaining state?","Both keep state between calls. A **closure** holds state in captured variables a\nreturned function reads\u002Fwrites. A **generator** pauses at `yield` and resumes,\npreserving its entire execution state — better for **sequences** and lazy\niteration.\n\n```js\n\u002F\u002F closure counter\nconst counter = (() => { let n = 0; return () => ++n })()\n\u002F\u002F generator counter\nfunction* gen() { let n = 0; while (true) yield ++n }\nconst g = gen()\ng.next().value \u002F\u002F 1\n```\n\nUse a closure for simple persistent state; a generator when you need to produce a\nstream of values or model a resumable process.\n",{"id":2234,"difficulty":84,"q":2235,"a":2236},"closure-react-stale","How do closures cause stale values in callbacks (e.g. React)?","A callback closes over the variables from the moment it was **created**. If those\nvalues change later but the callback isn't recreated, it keeps using the old\n(\"stale\") snapshot.\n\n```js\nlet count = 0\nconst timer = setInterval(() => console.log(count), 1000) \u002F\u002F always logs 0\ncount = 5 \u002F\u002F the closure captured the binding, but in React each render has its own\n```\n\nIn React, each render creates new closures over that render's props\u002Fstate, so an\neffect or event handler with stale deps logs old values. Fixes: include the value\nin dependencies, use a functional updater, or read the latest from a `ref`.\n",{"id":2238,"difficulty":84,"q":2239,"a":2240},"closure-gc","When is a closure's captured scope garbage collected?","A closure keeps its captured variables alive **as long as the closure itself is\nreachable**. Once nothing references the closure, the captured scope becomes\neligible for garbage collection.\n\n```js\nfunction make() {\n  const big = new Array(1e6)\n  return () => big.length\n}\nlet fn = make()  \u002F\u002F `big` is retained because fn closes over it\nfn = null        \u002F\u002F now `big` can be collected\n```\n\nEngines optimize by capturing only the variables actually used, but holding onto\nclosures (e.g. in a long-lived array or an un-removed event listener)\nindefinitely retains their scope — a common leak source.\n",{"id":2242,"difficulty":63,"q":2243,"a":2244},"nested-closures","How do nested closures work?","An inner function can close over variables from **multiple enclosing scopes** at\nonce, walking up the scope chain. Each level's variables remain accessible.\n\n```js\nfunction a(x) {\n  return function b(y) {\n    return function c(z) {\n      return x + y + z   \u002F\u002F closes over x (from a) AND y (from b)\n    }\n  }\n}\na(1)(2)(3) \u002F\u002F 6\n```\n\nThis layered capture is exactly how currying works. The innermost function holds\nreferences to every outer scope it uses, keeping them all alive.\n",{"id":2246,"difficulty":71,"q":2247,"a":2248},"closure-array-methods","How do closures appear in array method callbacks?","Callbacks passed to `map`\u002F`filter`\u002F`reduce` close over variables in their\nsurrounding scope, letting them reference outside data without extra parameters.\n\n```js\nfunction aboveThreshold(numbers, threshold) {\n  return numbers.filter(n => n > threshold) \u002F\u002F closes over `threshold`\n}\naboveThreshold([1, 5, 10], 4) \u002F\u002F [5, 10]\n```\n\nThe arrow remembers `threshold` from the enclosing function. This is closures at\nwork in everyday code, usually without anyone calling it \"a closure.\"\n",{"id":2250,"difficulty":84,"q":2251,"a":2252},"shared-state-bug","What bug arises when closures unexpectedly share state?","If multiple closures capture the **same** variable (instead of separate\nbindings), they all see and mutate one shared value — leading to surprising\ncoupling, like the `var` loop bug.\n\n```js\n\u002F\u002F all handlers share one `config` object\nconst config = {}\nconst handlers = sources.map(() => () => use(config)) \u002F\u002F same config\n```\n\nTo give each closure its own state, create a fresh scope per closure (a factory\ncall, an IIFE, or a block-scoped `let`). Recognizing shared vs independent capture\nis key to debugging closure issues.\n",{"id":2254,"difficulty":63,"q":2255,"a":2256},"closure-async-await","How do closures behave across async boundaries?","Variables captured by a closure remain valid **after** awaits and across async\ngaps — the closure keeps the scope alive. But beware capturing a value that\n**changes** during the wait.\n\n```js\nasync function process(items) {\n  for (const item of items) {\n    await save(item)\n    \u002F\u002F `item` is correctly captured per iteration (let\u002Fconst)\n  }\n}\n```\n\n`let`\u002F`const` loop variables give each iteration a fresh binding, so async\ncallbacks see the right value. With `var`, the shared binding would be stale by\nthe time the awaited work resumes.\n",{"id":2258,"difficulty":71,"q":2259,"a":2260},"counter-with-operations","How do you build an encapsulated counter with multiple operations?","Return an object whose methods all close over the same private variable, so they\nshare controlled access to it while the outside world can't touch it directly.\n\n```js\nfunction createCounter(start = 0) {\n  let count = start\n  return {\n    increment: () => ++count,\n    decrement: () => --count,\n    reset: () => (count = start),\n    value: () => count,\n  }\n}\nconst c = createCounter(10)\nc.increment(); c.value() \u002F\u002F 11\n```\n\nAll four methods operate on one private `count`. This is the closure-based\nalternative to a class with a private field.\n",{"id":2262,"difficulty":63,"q":2263,"a":2264},"closure-loop-fix-iife","How does an IIFE fix the var loop closure problem?","An IIFE creates a **new scope per iteration**, capturing the current value as a\nparameter so each callback closes over its own copy.\n\n```js\nfor (var i = 0; i \u003C 3; i++) {\n  (function (j) {\n    setTimeout(() => console.log(j), 100) \u002F\u002F j is this iteration's copy\n  })(i)\n}\n\u002F\u002F 0 1 2\n```\n\nThe IIFE is immediately invoked with `i`, binding it to the local `j`. This was\nthe standard pre-ES6 fix; today simply using `let` (which block-scopes per\niteration) is cleaner.\n",{"id":2266,"difficulty":63,"q":2267,"a":2268},"closure-overhead","Do closures have a performance or memory cost?","Each closure retains its captured variables in memory for as long as it lives, so\ncreating **many** closures (e.g. a new function per array element in a hot loop)\nuses more memory than sharing one function. Modern engines optimize aggressively,\ncapturing only used variables.\n\n```js\n\u002F\u002F creates N closures, each retaining scope\nitems.map(item => () => process(item))\n```\n\nIn practice closures are cheap and the readability\u002Fencapsulation wins outweigh the\ncost — but in performance-critical code with huge numbers of closures, reusing\nfunctions or avoiding unnecessary capture can matter.\n",{"id":2270,"difficulty":63,"q":2271,"a":2272},"closure-singleton","How do you implement a singleton with a closure?","An IIFE runs once and returns a single shared instance; the closure caches it so\nevery access returns the same object.\n\n```js\nconst config = (function () {\n  let instance\n  function create() { return { loadedAt: Date.now() } }\n  return {\n    get() {\n      if (!instance) instance = create() \u002F\u002F created once\n      return instance\n    },\n  }\n})()\nconfig.get() === config.get() \u002F\u002F true — same instance\n```\n\nThe private `instance` variable, hidden in the closure, guarantees a single\nshared object — the closure-based singleton pattern.\n",{"description":61},"JavaScript closure interview questions and answers — what closures are, how they capture variables, practical uses and common pitfalls.","javascript\u002Ffunctions\u002Fclosures","Functions","functions","fIkqXiaH8g__RSSbGGQQ3i6Y8gV63cRtxHtJRDtN9gg",{"id":2280,"title":2281,"body":2282,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":2286,"navigation":66,"order":40,"path":2287,"questions":2288,"related":207,"seo":2409,"seoDescription":2410,"stem":2411,"subtopic":2412,"topic":2276,"topicSlug":2277,"updated":214,"__hash__":2413},"qa\u002Fjavascript\u002Ffunctions\u002Ffunction-types-parameters.md","Function Types Parameters",{"type":58,"value":2283,"toc":2284},[],{"title":61,"searchDepth":22,"depth":22,"links":2285},[],{},"\u002Fjavascript\u002Ffunctions\u002Ffunction-types-parameters",[2289,2293,2297,2301,2305,2309,2313,2317,2321,2325,2329,2333,2337,2341,2345,2349,2353,2357,2361,2365,2369,2373,2377,2381,2385,2389,2393,2397,2401,2405],{"id":2290,"difficulty":71,"q":2291,"a":2292},"declaration-vs-expression","What is the difference between a function declaration and a function expression?","A **function declaration** stands alone as a statement and is **hoisted**\nwhole, so you can call it before its line. A **function expression** assigns a\nfunction to a variable; only the variable is hoisted, not its value.\n\n```js\nsayHi()                       \u002F\u002F works — declaration hoisted\nfunction sayHi() {}\n\nsayBye()                      \u002F\u002F TypeError: sayBye is not a function\nvar sayBye = function () {}   \u002F\u002F expression — value assigned at runtime\n```\n\n**Pitfall:** with `let`\u002F`const` the expression variable is in the temporal\ndead zone, so calling early throws a ReferenceError instead. Choose\ndeclarations for top-level reusable functions and expressions when passing a\nfunction as a value.\n",{"id":2294,"difficulty":71,"q":2295,"a":2296},"named-vs-anonymous","What is the difference between named and anonymous functions?","A **named function** has its own identifier; an **anonymous function** has\nnone. The name aids **recursion** and **stack traces**.\n\n```js\nconst fac = function factorial(n) {           \u002F\u002F named function expression\n  return n \u003C= 1 ? 1 : n * factorial(n - 1)    \u002F\u002F can call itself by name\n}\n\n[1].map(function () {})    \u002F\u002F anonymous — appears unnamed in traces\n```\n\nModern engines infer a name for anonymous functions assigned to a variable, so\n`const f = () => {}` has `f.name === 'f'`. **Pitfall:** a named function\nexpression's inner name is only visible **inside** the function, not outside.\n",{"id":2298,"difficulty":63,"q":2299,"a":2300},"arrow-vs-regular","How do arrow functions differ from regular functions?","Arrow functions are more than shorter syntax. They have **no own `this`,\n`arguments`, `super`, or `new.target`** — they inherit `this` lexically — and\nthey **cannot be used as constructors**.\n\n```js\nconst obj = {\n  items: [1, 2],\n  log() {\n    this.items.forEach(i => console.log(this.items))  \u002F\u002F `this` is obj\n  }\n}\nconst Arrow = () => {}\nnew Arrow()   \u002F\u002F TypeError: Arrow is not a constructor\n```\n\n**Pitfall:** don't use an arrow as an object **method** if you need `this` to\nbe the object — it will be the surrounding scope's `this` (often the module or\nwindow), not the object.\n",{"id":2302,"difficulty":63,"q":2303,"a":2304},"what-is-iife","What is an IIFE and why use one?","An **IIFE (Immediately Invoked Function Expression)** is a function defined and\ncalled at once. It creates a **private scope** so its variables don't leak.\n\n```js\n(function () {\n  const secret = 42        \u002F\u002F not visible outside\n  console.log(secret)\n})()                       \u002F\u002F runs immediately\n\n\u002F\u002F arrow form\n(() => { \u002F* ... *\u002F })()\n```\n\nThe wrapping parens turn the declaration into an **expression** so it can be\ninvoked. IIFEs powered the old **module pattern** before ES modules. **Pitfall:**\na missing semicolon before an IIFE can make the previous line try to call it —\ndefensively prefix with `;`.\n",{"id":2306,"difficulty":71,"q":2307,"a":2308},"first-class-functions","What does it mean that functions are first-class in JavaScript?","**First-class** means functions are treated like any other **value**: they can\nbe assigned to variables, stored in arrays\u002Fobjects, passed as arguments, and\nreturned from functions.\n\n```js\nconst ops = { add: (a, b) => a + b }   \u002F\u002F stored in an object\nconst fns = [Math.abs, Math.sqrt]      \u002F\u002F stored in an array\nconst run = fn => fn(16)               \u002F\u002F passed as argument\nrun(fns[1])   \u002F\u002F 4\n```\n\nThis is the foundation that makes **higher-order functions, callbacks, and\nclosures** possible. Without first-class functions, none of the functional\npatterns in JS would work.\n",{"id":2310,"difficulty":71,"q":2311,"a":2312},"default-parameters","How do default parameters work?","A **default parameter** supplies a value when the argument is **`undefined`**\n(either omitted or explicitly `undefined`). The default expression is\nevaluated **at call time**, only when needed.\n\n```js\nfunction greet(name = 'friend') { return `Hi, ${name}` }\ngreet()           \u002F\u002F 'Hi, friend'\ngreet(undefined)  \u002F\u002F 'Hi, friend'   — default applies\ngreet(null)       \u002F\u002F 'Hi, null'     null is NOT undefined\n```\n\n**Pitfall:** only `undefined` triggers the default — passing `null`, `0`, or\n`''` does not. Defaults can also reference **earlier parameters**:\n`(a, b = a * 2) => ...`.\n",{"id":2314,"difficulty":84,"q":2315,"a":2316},"defaults-evaluation-order","When are default parameter expressions evaluated, and in what order?","Defaults are evaluated **left to right at call time**, each in a scope where\n**earlier parameters are already bound** but later ones are not. They are fresh\nevery call, not cached.\n\n```js\nlet calls = 0\nconst next = () => ++calls\nfunction f(a = next(), b = a + 1) { return [a, b] }\nf()      \u002F\u002F [1, 2]   — next() ran once, b saw a\nf(10)    \u002F\u002F [10, 11] — default for a skipped, next() not called\n```\n\n**Pitfall:** referencing a **later** parameter in an earlier default throws a\nReferenceError (TDZ): `function g(a = b, b = 1) {}` — `g()`. Also, an object\ndefault like `{ items: [] }` creates a **new array each call**, avoiding the\nshared-mutable-default trap seen in some other languages.\n",{"id":2318,"difficulty":63,"q":2319,"a":2320},"rest-parameters","What are rest parameters?","A **rest parameter** (`...args`) collects all remaining arguments into a\n**real array**. It must be the **last** parameter and there can be only one.\n\n```js\nfunction sum(...nums) {\n  return nums.reduce((a, b) => a + b, 0)   \u002F\u002F nums is a true array\n}\nsum(1, 2, 3)   \u002F\u002F 6\n\nfunction tagged(first, ...rest) { \u002F* first separate, rest gathers the tail *\u002F }\n```\n\nUnlike the old `arguments` object, rest params are a genuine `Array` (with\n`map`, `filter`, etc.). **Pitfall:** rest params are **excluded** from\n`fn.length` (arity).\n",{"id":2322,"difficulty":63,"q":2323,"a":2324},"arguments-object","What is the arguments object?","`arguments` is an **array-like** object available inside **regular** (non-arrow)\nfunctions, holding **all** passed arguments regardless of declared parameters.\n\n```js\nfunction f() {\n  return arguments.length          \u002F\u002F works even with no named params\n}\nf(1, 2, 3)   \u002F\u002F 3\n\n\u002F\u002F it's array-LIKE, not an array\nArray.prototype.slice.call(arguments)   \u002F\u002F convert to real array\n[...arguments]                          \u002F\u002F modern conversion\n```\n\n**Pitfall:** it lacks array methods (`map`, `forEach`), so convert it first.\nIn modern code, prefer **rest parameters** over `arguments`.\n",{"id":2326,"difficulty":63,"q":2327,"a":2328},"why-arrows-no-arguments","Why don't arrow functions have their own arguments object?","Arrow functions deliberately have **no own `arguments`** — like `this`, they\ninherit it lexically from the enclosing **regular** function (or it's\nundefined at module top level).\n\n```js\nfunction outer() {\n  const inner = () => arguments[0]   \u002F\u002F refers to outer's arguments\n  return inner()\n}\nouter('hi')   \u002F\u002F 'hi'\n\nconst f = () => arguments   \u002F\u002F ReferenceError at top level\n```\n\nThe fix when you need all args in an arrow is **rest parameters**:\n`const f = (...args) => args`. This lexical behavior is exactly why arrows are\ngreat as callbacks but unsuitable as methods needing their own `arguments`.\n",{"id":2330,"difficulty":63,"q":2331,"a":2332},"function-length","What does a function's length property return?","`fn.length` is the function's **arity** — the number of parameters **before**\nthe first one with a default value or a rest parameter. It does **not** count\nthose.\n\n```js\n((a, b) => {}).length        \u002F\u002F 2\n((a, b = 1) => {}).length    \u002F\u002F 1   — stops at first default\n((a, ...rest) => {}).length  \u002F\u002F 1   — rest excluded\n((a, b, c = 1, d) => {}).length \u002F\u002F 2 — counts up to first default\n```\n\n**Pitfall:** because defaults and rest reduce `length`, generic helpers like\n`curry` that rely on `fn.length` misbehave on such functions. `length` is\nread-only.\n",{"id":2334,"difficulty":71,"q":2335,"a":2336},"function-name","How is a function's name property determined?","`fn.name` is the function's name string, used in **stack traces** and\ndebugging. Engines **infer** it from the variable or property a function is\nassigned to when the function itself is anonymous.\n\n```js\nfunction foo() {}\nfoo.name                 \u002F\u002F 'foo'\nconst bar = () => {}\nbar.name                 \u002F\u002F 'bar'    — inferred\nconst o = { baz() {} }\no.baz.name               \u002F\u002F 'baz'\n[].map(() => {}).name    \u002F\u002F '' or anonymous — not assigned to a binding\n```\n\n`bind` prepends `'bound '`: `foo.bind(null).name === 'bound foo'`. **Pitfall:**\nminifiers rename functions, so don't rely on `name` for program logic.\n",{"id":2338,"difficulty":63,"q":2339,"a":2340},"parameter-destructuring","How does parameter destructuring work?","You can **destructure** an object or array argument right in the parameter\nlist, pulling out the fields you need and optionally giving them defaults.\n\n```js\nfunction createUser({ name, role = 'user', age } = {}) {\n  return `${name} (${role})`\n}\ncreateUser({ name: 'Ada', role: 'admin' })   \u002F\u002F 'Ada (admin)'\ncreateUser()                                  \u002F\u002F 'undefined (user)' no crash\n```\n\nThe trailing `= {}` is crucial: it lets the function be **called with no\nargument** without throwing. **Pitfall:** omitting it and calling\n`createUser()` throws \"Cannot destructure property of undefined\".\n",{"id":2342,"difficulty":71,"q":2343,"a":2344},"methods-vs-functions","What is the difference between a method and a function?","A **method** is simply a function stored as an **object property** and usually\ncalled with a receiver (`obj.method()`), so its `this` is that object. A plain\n**function** is called standalone and its `this` depends on call context.\n\n```js\nconst calc = {\n  value: 10,\n  double() { return this.value * 2 }   \u002F\u002F method — `this` is calc\n}\ncalc.double()   \u002F\u002F 20\n\nconst d = calc.double\nd()             \u002F\u002F `this` is undefined — now a detached function call\n```\n\n**Pitfall:** detaching a method (`const d = calc.double`) loses the receiver;\n`this` is determined by **how** it's called, not where it lives.\n",{"id":2346,"difficulty":63,"q":2347,"a":2348},"shorthand-method","What is method shorthand and how does it differ from a property holding a function?","**Method shorthand** (`foo() {}` inside an object) is mostly equivalent to\n`foo: function () {}`, but shorthand methods can use **`super`** and are\ncreated as **non-constructable** (you can't `new` them).\n\n```js\nconst obj = {\n  greet() { return 'hi' },             \u002F\u002F shorthand\n  greet2: function () { return 'hi' }  \u002F\u002F property with function\n}\nnew obj.greet2()   \u002F\u002F works (legacy)\nnew obj.greet()    \u002F\u002F TypeError: not a constructor\n```\n\n**Pitfall:** the inability to construct shorthand methods is by design; it's\nrarely an issue but surprising if you relied on it.\n",{"id":2350,"difficulty":63,"q":2351,"a":2352},"recursion-basics","What is recursion and what does every recursive function need?","**Recursion** is a function calling **itself** to solve a smaller version of a\nproblem. Every recursive function needs a **base case** that stops the\nrecursion and a **recursive case** that moves toward it.\n\n```js\nfunction factorial(n) {\n  if (n \u003C= 1) return 1          \u002F\u002F base case\n  return n * factorial(n - 1)   \u002F\u002F recursive case, n shrinks\n}\nfactorial(5)   \u002F\u002F 120\n```\n\n**Pitfall:** a missing or unreachable base case causes infinite recursion and\na **\"Maximum call stack size exceeded\"** error. Deep recursion can also blow\nthe stack even when correct.\n",{"id":2354,"difficulty":84,"q":2355,"a":2356},"tail-call","What is a tail call, and does JavaScript optimize them?","A **tail call** is when a function's **last action** is to return the result of\nanother call, with nothing left to do afterward. Proper Tail Calls (PTC) would\nlet the engine **reuse the stack frame**, enabling unbounded recursion.\n\n```js\nfunction fact(n, acc = 1) {\n  if (n \u003C= 1) return acc\n  return fact(n - 1, n * acc)   \u002F\u002F tail position — no pending multiply\n}\n```\n\n**Reality:** although PTC is in the ES2015 spec, **only Safari\u002FJavaScriptCore**\nimplements it; V8 (Chrome\u002FNode) and Firefox do not. **Pitfall:** so don't rely\non tail-call elimination for deep recursion — use a loop or an explicit stack\ninstead.\n",{"id":2358,"difficulty":71,"q":2359,"a":2360},"arity-definition","What is arity?","**Arity** is the **number of arguments a function expects** — its declared\nparameter count, reflected (with caveats) by `fn.length`.\n\n```js\nconst unary  = x => x         \u002F\u002F arity 1\nconst binary = (a, b) => a+b  \u002F\u002F arity 2\nbinary.length   \u002F\u002F 2\n```\n\nSome HOFs depend on arity — e.g. a `curry` helper invokes once enough args\narrive. **Pitfall:** \"expected\" arity (`length`) and \"actual\" args passed can\ndiffer freely in JS, since extra args are ignored and missing ones become\n`undefined`.\n",{"id":2362,"difficulty":63,"q":2363,"a":2364},"variadic-functions","What is a variadic function?","A **variadic** function accepts a **variable number of arguments**. In modern\nJS you express this with a **rest parameter**; older code read `arguments`.\n\n```js\nconst max = (...nums) => nums.reduce((m, n) => n > m ? n : m, -Infinity)\nmax(3, 9, 2)        \u002F\u002F 9\nmax(...[5, 1, 8])   \u002F\u002F 8   — spread an array in\n\nMath.max(1, 2, 3)   \u002F\u002F built-in variadic example\n```\n\n**Pitfall:** spreading a **very large** array into a variadic call can exceed\nthe engine's argument limit and throw — use `reduce` over the array directly\nfor huge inputs.\n",{"id":2366,"difficulty":63,"q":2367,"a":2368},"pass-by-value-reference","Are function arguments passed by value or by reference in JavaScript?","JavaScript is **pass-by-value** for everything — but for objects the \"value\"\nis a **reference** (a copy of the pointer). So you can mutate an object's\ncontents, but **reassigning** the parameter doesn't affect the caller.\n\n```js\nfunction mutate(o) { o.x = 1 }      \u002F\u002F caller sees x === 1\nfunction reassign(o) { o = { x: 9 } } \u002F\u002F caller unaffected\n\nconst a = {}; mutate(a)    \u002F\u002F a.x === 1\nconst b = {}; reassign(b)  \u002F\u002F b unchanged\n```\n\n**Pitfall:** this trips people who expect \"pass by reference\" — only the\n**reference is copied**, so reassigning the local parameter is invisible to\nthe caller.\n",{"id":2370,"difficulty":71,"q":2371,"a":2372},"optional-arguments","What happens when you call a function with fewer or more arguments than declared?","JavaScript is **lenient about arity**. Missing arguments are `undefined`; extra\narguments are **ignored** (but still available via `arguments`\u002Frest).\n\n```js\nfunction f(a, b) { return [a, b] }\nf(1)         \u002F\u002F [1, undefined]   — missing -> undefined\nf(1, 2, 3)   \u002F\u002F [1, 2]           — extra 3 ignored by params\n```\n\nThis flexibility powers default parameters and variadic patterns. **Pitfall:**\nbecause no error is thrown, a typo dropping an argument fails silently with\n`undefined` downstream rather than at the call site.\n",{"id":2374,"difficulty":84,"q":2375,"a":2376},"function-constructor","What is the Function constructor and why avoid it?","The **`Function` constructor** builds a function from **strings** at runtime:\n`new Function('a', 'b', 'return a + b')`. Like `eval`, it executes dynamic\ncode.\n\n```js\nconst add = new Function('a', 'b', 'return a + b')\nadd(2, 3)   \u002F\u002F 5\n\n\u002F\u002F does NOT close over local scope\nfunction outer() {\n  const x = 1\n  return new Function('return x')   \u002F\u002F ReferenceError when called\n}\n```\n\n**Avoid it** because: it bypasses **lexical scope** (only sees global), is a\n**security\u002FCSP risk**, and can't be optimized. Use real functions or closures\ninstead.\n",{"id":2378,"difficulty":63,"q":2379,"a":2380},"generator-function-type","How is a generator function syntactically different from a normal function?","A **generator function** is declared with `function*` and can **pause** at\n`yield`. Calling it doesn't run the body — it returns an **iterator** object.\n\n```js\nfunction* gen() { yield 1; yield 2 }\nconst it = gen()        \u002F\u002F nothing logged yet\nit.next()               \u002F\u002F { value: 1, done: false }\n```\n\nIt's a distinct function *type* from declarations, expressions, and arrows.\n**Pitfall:** there is **no arrow generator** syntax — `*() => {}` is invalid;\ngenerators must use `function*`.\n",{"id":2382,"difficulty":63,"q":2383,"a":2384},"async-function-type","What makes an async function a distinct function type?","An **`async` function** always **returns a Promise** and may use `await`\ninside to pause until a Promise settles. The `async` keyword changes the\nfunction's return contract.\n\n```js\nasync function load() {\n  const r = await fetch('\u002Fapi')   \u002F\u002F pauses without blocking the thread\n  return r.json()                  \u002F\u002F wrapped in a Promise automatically\n}\nload().then(data => \u002F* ... *\u002F data)   \u002F\u002F returns a Promise\n```\n\nArrows can be async too: `const f = async () => {}`. **Pitfall:** even a\n`return 5` inside an async function yields `Promise\u003C5>`, not `5`, so callers\nmust `await` or `.then` it.\n",{"id":2386,"difficulty":63,"q":2387,"a":2388},"constructor-functions","What is a constructor function and how is `new` involved?","A **constructor function** is a regular function intended to be called with\n**`new`**. `new` creates a fresh object, sets its prototype, binds `this` to\nit, runs the body, and returns the object.\n\n```js\nfunction User(name) { this.name = name }   \u002F\u002F convention: capitalized\nconst u = new User('Ada')   \u002F\u002F this -> new object\nUser('Bob')                 \u002F\u002F no `new`: `this` is undefined\u002Fglobal\n```\n\n**Pitfall:** forgetting `new` is a classic bug — `this` leaks to the global\nobject (or throws in strict mode). ES6 **classes** make this safer by throwing\nif you call them without `new`.\n",{"id":2390,"difficulty":84,"q":2391,"a":2392},"hoisting-fn-vs-class","How does hoisting differ between function declarations and function expressions assigned to let\u002Fconst?","**Function declarations** are fully hoisted — name and body — so they're\ncallable from the top of the scope. **`let`\u002F`const` expressions** are hoisted\nonly as **uninitialized bindings** in the temporal dead zone (TDZ).\n\n```js\ndecl()            \u002F\u002F works\nfunction decl() {}\n\nexpr()            \u002F\u002F ReferenceError — TDZ\nconst expr = () => {}\n```\n\nWith `var`, the variable hoists as `undefined`, so calling early gives a\n**TypeError** (`undefined is not a function`) instead. **Pitfall:** relying on\ndeclaration hoisting can obscure code order — many style guides discourage it.\n",{"id":2394,"difficulty":63,"q":2395,"a":2396},"default-with-rest","Can you combine default parameters, destructuring, and rest in one signature?","Yes — JS lets you mix all parameter features, though **rest must come last**\nand a rest parameter **cannot have a default**.\n\n```js\nfunction config({ debug = false } = {}, ...plugins) {\n  return { debug, count: plugins.length }\n}\nconfig({ debug: true }, 'a', 'b')   \u002F\u002F { debug: true, count: 2 }\n\nfunction bad(...args = []) {}   \u002F\u002F SyntaxError — rest can't default\n```\n\n**Pitfall:** ordering matters — a default-valued parameter after a rest\nparameter is a syntax error, and forgetting the `= {}` on the destructured\nobject breaks no-argument calls.\n",{"id":2398,"difficulty":63,"q":2399,"a":2400},"closures-over-params","How do parameters participate in closures?","Parameters are **local variables** of a function, so an inner function closes\nover them just like any other local. This is the basis of **factory functions**\nand partial application.\n\n```js\nfunction multiplier(factor) {        \u002F\u002F `factor` is a parameter...\n  return n => n * factor             \u002F\u002F ...captured by the returned closure\n}\nconst triple = multiplier(3)\ntriple(5)   \u002F\u002F 15   factor remembered\n```\n\nEach call to `multiplier` creates a **new** `factor` binding, so `double` and\n`triple` don't interfere. **Pitfall:** capturing a parameter that's later\nreassigned inside the outer function captures the **latest** value, not a\nsnapshot.\n",{"id":2402,"difficulty":84,"q":2403,"a":2404},"getter-setter-functions","How do getter and setter functions differ from normal methods?","**Getters\u002Fsetters** are functions defined with `get`\u002F`set` that are invoked by\n**property access syntax** rather than a call — `obj.x` runs the getter,\n`obj.x = 1` runs the setter.\n\n```js\nconst temp = {\n  _c: 0,\n  get fahrenheit() { return this._c * 9\u002F5 + 32 },\n  set fahrenheit(f) { this._c = (f - 32) * 5\u002F9 }\n}\ntemp.fahrenheit = 212   \u002F\u002F calls setter\ntemp.fahrenheit         \u002F\u002F 212 — calls getter, no parentheses\n```\n\nThey enable **computed\u002Fvalidated properties** with a plain-property API.\n**Pitfall:** a getter that does heavy work runs on **every access**, and a\ngetter without a matching setter makes the property silently read-only (or\nthrows in strict mode on assignment).\n",{"id":2406,"difficulty":84,"q":2407,"a":2408},"named-fn-expr-scope","Where is the name of a named function expression visible?","The name of a **named function expression** is bound **only inside the\nfunction's own body**, not in the surrounding scope. It exists so the function\ncan refer to itself.\n\n```js\nconst f = function rec(n) {\n  return n \u003C= 0 ? 0 : n + rec(n - 1)   \u002F\u002F `rec` visible here\n}\nf(3)    \u002F\u002F 6\nrec(3)  \u002F\u002F ReferenceError — `rec` not visible outside\n```\n\nThis makes recursion **safe against reassignment** of the outer variable\n(`f`). **Pitfall:** people expect the inner name to be accessible globally and\nare surprised by the ReferenceError outside.\n",{"description":61},"JavaScript function types and parameters interview questions — declarations vs expressions vs arrows, IIFEs, default and rest parameters, the arguments object, destructuring, arity, and first-class functions.","javascript\u002Ffunctions\u002Ffunction-types-parameters","Function Types & Parameters","MiP0SVPSrtWDSewPOQD8HZryX7lAoHl2TtUKXP5mnFQ",{"id":2415,"title":2416,"body":2417,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":2421,"navigation":66,"order":50,"path":2422,"questions":2423,"related":207,"seo":2543,"seoDescription":2544,"stem":2545,"subtopic":2546,"topic":2276,"topicSlug":2277,"updated":214,"__hash__":2547},"qa\u002Fjavascript\u002Ffunctions\u002Fgenerators-iterators.md","Generators Iterators",{"type":58,"value":2418,"toc":2419},[],{"title":61,"searchDepth":22,"depth":22,"links":2420},[],{},"\u002Fjavascript\u002Ffunctions\u002Fgenerators-iterators",[2424,2428,2432,2436,2440,2444,2448,2452,2456,2460,2464,2468,2472,2476,2480,2484,2488,2492,2496,2500,2504,2507,2511,2515,2519,2523,2527,2531,2535,2539],{"id":2425,"difficulty":63,"q":2426,"a":2427},"iterator-protocol","What is the iterator protocol?","An **iterator** is any object with a **`next()`** method that returns\n`{ value, done }` on each call — `done: true` signals the end.\n\n```js\nconst it = {\n  i: 0,\n  next() {\n    return this.i \u003C 3\n      ? { value: this.i++, done: false }\n      : { value: undefined, done: true }   \u002F\u002F terminator\n  }\n}\nit.next()  \u002F\u002F { value: 0, done: false }\n```\n\nAnything implementing this shape can be driven manually, but usually you\nconsume iterators through `for...of`, spread, or destructuring.\n",{"id":2429,"difficulty":63,"q":2430,"a":2431},"iterable-protocol","What is the iterable protocol and how does it relate to iterators?","An **iterable** is an object with a **`[Symbol.iterator]()`** method that\n*returns an iterator*. The iterable is the collection; the iterator is the\ncursor over it.\n\n```js\nconst range = {\n  [Symbol.iterator]() {\n    let n = 0\n    return { next: () => n \u003C 3\n      ? { value: n++, done: false }\n      : { value: undefined, done: true } }\n  }\n}\n[...range]   \u002F\u002F [0, 1, 2]  now spreadable \u002F for-of-able\n```\n\n`for...of`, spread, `Array.from`, and destructuring all call\n`Symbol.iterator` under the hood.\n",{"id":2433,"difficulty":71,"q":2434,"a":2435},"builtin-iterables","Which built-in types are iterable?","Arrays, strings, `Map`, `Set`, `arguments`, `TypedArray`, and DOM\ncollections like `NodeList` — all ship a `Symbol.iterator`.\n\n```js\nfor (const ch of 'hi') {}        \u002F\u002F strings\nfor (const [k, v] of map) {}     \u002F\u002F Map yields [key, value]\n```\n\nNotably **plain objects are NOT iterable** — `for...of {}` throws. Use\n`Object.keys\u002Fvalues\u002Fentries`, which return iterable arrays.\n",{"id":2437,"difficulty":71,"q":2438,"a":2439},"generator-basics","What is a generator function?","A **generator** (`function*`) is a function that can **pause and resume**.\nCalling it doesn't run the body — it returns a **generator object** (which\nis both an iterator and iterable). Each `next()` runs to the next `yield`.\n\n```js\nfunction* gen() {\n  yield 1\n  yield 2\n}\nconst g = gen()\ng.next()  \u002F\u002F { value: 1, done: false }\ng.next()  \u002F\u002F { value: 2, done: false }\ng.next()  \u002F\u002F { value: undefined, done: true }\n```\n\nGenerators are the easiest way to build custom iterators without writing\n`next()` by hand.\n",{"id":2441,"difficulty":71,"q":2442,"a":2443},"yield-keyword","What does the yield keyword do?","**`yield`** pauses the generator and emits a value to the caller. Execution\nfreezes — local variables and position are preserved — until the next\n`next()` resumes it right after that `yield`.\n\n```js\nfunction* counter() {\n  let n = 0\n  while (true) yield n++   \u002F\u002F resumes here each time\n}\n```\n\nThis pause\u002Fresume is what makes lazy and infinite sequences possible.\n",{"id":2445,"difficulty":63,"q":2446,"a":2447},"generator-is-iterable","Why can you use a generator directly in for...of and spread?","A generator object implements **both** protocols: it has `next()` (it's an\niterator) and a `Symbol.iterator` that returns itself (it's iterable).\n\n```js\nfunction* g() { yield 'a'; yield 'b' }\n[...g()]                 \u002F\u002F ['a', 'b']\nfor (const x of g()) {}  \u002F\u002F works directly\n```\n\nBecause it returns *itself* from `Symbol.iterator`, a generator is a\n**one-shot** iterable — once consumed it's exhausted.\n",{"id":2449,"difficulty":63,"q":2450,"a":2451},"custom-iterable-with-generator","How do generators simplify making a class iterable?","Define `[Symbol.iterator]` as a **generator method**; `yield` the elements\nand the protocol bookkeeping is handled for you.\n\n```js\nclass Range {\n  constructor(s, e) { this.s = s; this.e = e }\n  *[Symbol.iterator]() {\n    for (let i = this.s; i \u003C this.e; i++) yield i  \u002F\u002F\n  }\n}\n[...new Range(1, 4)]   \u002F\u002F [1, 2, 3]\n```\n\nCompare to the manual `next()`\u002F`done` version — the generator removes all\nthe state plumbing.\n",{"id":2453,"difficulty":63,"q":2454,"a":2455},"lazy-evaluation","What does it mean that generators are lazy?","Values are produced **on demand**, only when `next()` asks. Nothing is\ncomputed until consumed, and computation stops as soon as the consumer\nstops.\n\n```js\nfunction* squares() { let n = 1; while (true) yield n * n++ }\nconst it = squares()\nit.next().value  \u002F\u002F 1   — only this much computed\nit.next().value  \u002F\u002F 4\n```\n\nThis lets you model infinite or expensive sequences and pull just the\nfirst few elements without computing the rest.\n",{"id":2457,"difficulty":63,"q":2458,"a":2459},"infinite-sequence","How do you build an infinite sequence safely?","A generator with an unbounded loop is fine **as long as the consumer\nbounds it**.\n\n```js\nfunction* naturals() { let n = 1; while (true) yield n++ }\nfunction take(it, k) {\n  const out = []\n  for (const x of it) { out.push(x); if (out.length === k) break }\n  return out\n}\ntake(naturals(), 3)   \u002F\u002F [1, 2, 3]\n```\n\nThe pitfall: `[...naturals()]` or `for...of` without a `break` will loop\nforever. Always cap consumption.\n",{"id":2461,"difficulty":63,"q":2462,"a":2463},"yield-delegation","What does yield* (delegation) do?","**`yield*`** delegates to another iterable\u002Fgenerator — it yields *all* of\nits values in place, as if inlined.\n\n```js\nfunction* inner() { yield 1; yield 2 }\nfunction* outer() {\n  yield 0\n  yield* inner()   \u002F\u002F yields 1 then 2\n  yield 3\n}\n[...outer()]   \u002F\u002F [0, 1, 2, 3]\n```\n\nIt also forwards the delegated generator's **return value** as the result\nof the `yield*` expression, useful for composing generators.\n",{"id":2465,"difficulty":63,"q":2466,"a":2467},"yield-delegation-any-iterable","Can yield* delegate to non-generator iterables?","Yes — `yield*` works on any iterable, so you can flatten arrays, strings,\nSets, etc.\n\n```js\nfunction* flatten(arrs) {\n  for (const a of arrs) yield* a   \u002F\u002F spread each array's items\n}\n[...flatten([[1, 2], [3], [4, 5]])]  \u002F\u002F [1, 2, 3, 4, 5]\n```\n\nThis makes recursive flattening of nested structures elegant — just\n`yield* flatten(child)` for sub-arrays.\n",{"id":2469,"difficulty":84,"q":2470,"a":2471},"passing-values-into-next","How do you pass a value back into a generator?","The argument to **`next(value)`** becomes the *result* of the `yield`\nexpression that the generator is paused on — two-way communication.\n\n```js\nfunction* convo() {\n  const name = yield 'What is your name?'\n  yield `Hello, ${name}!`\n}\nconst c = convo()\nc.next().value        \u002F\u002F 'What is your name?'\nc.next('Ada').value   \u002F\u002F 'Hello, Ada!'  'Ada' became `name`\n```\n\nGotcha: the **first** `next()` argument is ignored — there's no paused\n`yield` yet to receive it.\n",{"id":2473,"difficulty":84,"q":2474,"a":2475},"generator-return-method","What does the generator's return() method do?","`gen.return(v)` forces the generator to finish early, yielding\n`{ value: v, done: true }` and running any `finally` blocks for cleanup.\n\n```js\nfunction* g() {\n  try { yield 1; yield 2 }\n  finally { console.log('cleanup') }  \u002F\u002F runs on early return\n}\nconst it = g()\nit.next()        \u002F\u002F { value: 1, done: false }\nit.return(99)    \u002F\u002F logs 'cleanup'; { value: 99, done: true }\n```\n\n`for...of` calls `return()` automatically when you `break`, so resources\nget released.\n",{"id":2477,"difficulty":84,"q":2478,"a":2479},"generator-throw-method","What does the generator's throw() method do?","`gen.throw(err)` injects an exception **at the paused `yield`**, as if the\n`yield` itself threw — the generator can `try\u002Fcatch` it.\n\n```js\nfunction* g() {\n  try { yield 1 }\n  catch (e) { yield `caught ${e}` }  \u002F\u002F\n}\nconst it = g()\nit.next()          \u002F\u002F { value: 1 }\nit.throw('boom')   \u002F\u002F { value: 'caught boom', done: false }\n```\n\nIf the generator doesn't catch it, the error propagates to the caller of\n`throw()`.\n",{"id":2481,"difficulty":63,"q":2482,"a":2483},"return-value-in-generator","What happens to a return statement inside a generator?","A `return x` sets `{ value: x, done: true }` on the final `next()` — but\n**`for...of` and spread ignore that value**; they only collect yielded\nvalues.\n\n```js\nfunction* g() { yield 1; return 99 }\n[...g()]                  \u002F\u002F [1]  — 99 dropped\nconst it = g()\nit.next()                 \u002F\u002F { value: 1, done: false }\nit.next()                 \u002F\u002F { value: 99, done: true }  visible here\n```\n\nTo observe the return value you must drive `next()` manually or capture it\nvia `yield*`.\n",{"id":2485,"difficulty":84,"q":2486,"a":2487},"state-machine","How can a generator model a state machine?","Sequential `yield`s with a surrounding loop naturally encode states —\nexecution position *is* the current state, so you avoid explicit state\nvariables.\n\n```js\nfunction* traffic() {\n  while (true) {\n    yield 'green'; yield 'yellow'; yield 'red'  \u002F\u002F cycles states\n  }\n}\nconst light = traffic()\nlight.next().value  \u002F\u002F 'green'\nlight.next().value  \u002F\u002F 'yellow'\n```\n\nThe generator remembers where it paused, so each `next()` advances the\nmachine one transition with no bookkeeping.\n",{"id":2489,"difficulty":63,"q":2490,"a":2491},"generator-vs-array","When is a generator better than building an array?","When the sequence is **large, infinite, or expensive**, and the consumer\nmay not need all of it. A generator streams values lazily; an array\nmaterializes everything up front.\n\n```js\n\u002F\u002F reads a huge file line by line without loading it all\nfunction* lines(text) {\n  for (const line of text.split('\\n')) yield line.trim()\n}\n```\n\nFor small, fully-consumed collections an array is simpler and faster to\nindex — generators shine on streaming\u002Fpipeline workloads.\n",{"id":2493,"difficulty":63,"q":2494,"a":2495},"early-break-cleanup","What happens to a generator when you break out of for...of early?","`for...of` calls the iterator's **`return()`** on `break`, `throw`, or an\nexception — so a generator's `finally` runs and resources are released.\n\n```js\nfunction* withResource() {\n  try { while (true) yield acquire() }\n  finally { release() }   \u002F\u002F runs even on early break\n}\nfor (const x of withResource()) { if (done) break }  \u002F\u002F release() called\n```\n\nThis automatic cleanup is a key reason to wrap resource handling in\ntry\u002Ffinally inside generators.\n",{"id":2497,"difficulty":63,"q":2498,"a":2499},"spread-consumes-iterator","Why does iterating the same generator twice yield nothing the second time?","A generator object is a **single-use** iterator — once `done`, it stays\ndone. It doesn't restart.\n\n```js\nconst g = (function* () { yield 1; yield 2 })()\n[...g]   \u002F\u002F [1, 2]\n[...g]   \u002F\u002F []  already exhausted\n```\n\nTo re-iterate, expose a **factory** (a function returning a fresh\ngenerator) or a class whose `[Symbol.iterator]` creates a new one each\ncall.\n",{"id":2501,"difficulty":84,"q":2502,"a":2503},"async-generator","What is an async generator?","An **`async function*`** can `await` inside and `yield` values\nasynchronously. Its `next()` returns a **Promise** of `{ value, done }`,\nand you consume it with **`for await...of`**.\n\n```js\nasync function* pages(url) {\n  let next = url\n  while (next) {\n    const res = await fetch(next)   \u002F\u002F await inside\n    const data = await res.json()\n    yield data.items\n    next = data.nextPage\n  }\n}\nfor await (const items of pages('\u002Fapi')) { \u002F* ... *\u002F }\n```\n\nPerfect for paginated APIs and streams where each chunk arrives over time.\n",{"id":1621,"difficulty":84,"q":2505,"a":2506},"What is for await...of and where can you use it?","It iterates an **async iterable** (one with `Symbol.asyncIterator`),\nawaiting each `next()` Promise before the loop body runs. It must be inside\nan `async` function.\n\n```js\nasync function read(stream) {\n  for await (const chunk of stream) {   \u002F\u002F awaits each chunk\n    process(chunk)\n  }\n}\n```\n\nIt also works on a plain array of Promises, awaiting each in turn — handy\nfor sequential async processing.\n",{"id":2508,"difficulty":84,"q":2509,"a":2510},"symbol-asynciterator","How does Symbol.asyncIterator differ from Symbol.iterator?","`Symbol.iterator` returns an iterator whose `next()` yields plain\n`{ value, done }`; `Symbol.asyncIterator` returns one whose `next()` yields\na **Promise** of that. `for await...of` looks for `asyncIterator` first,\nfalling back to the sync one.\n\n```js\nconst stream = {\n  async *[Symbol.asyncIterator]() {\n    yield await getChunk()   \u002F\u002F async iterable\n  }\n}\n```\n\nUse the async variant when each value depends on I\u002FO or timing.\n",{"id":2512,"difficulty":63,"q":2513,"a":2514},"generator-memory","How do generators help with memory usage?","They hold only the **current** value and the suspended call frame, not the\nwhole sequence — so you can process gigabytes by streaming a constant\namount of memory.\n\n```js\nfunction* range(n) { for (let i = 0; i \u003C n; i++) yield i }\nlet sum = 0\nfor (const i of range(1e9)) sum += i   \u002F\u002F no billion-element array\n```\n\nBuilding `Array.from({length: 1e9})` first would blow the heap; the\ngenerator never allocates it.\n",{"id":2516,"difficulty":84,"q":2517,"a":2518},"generator-pipeline","How do you compose generators into a processing pipeline?","Chain generators that each take an iterable and yield a transformed one —\nlazy `map`\u002F`filter` that never build intermediate arrays.\n\n```js\nfunction* map(it, f) { for (const x of it) yield f(x) }\nfunction* filter(it, p) { for (const x of it) if (p(x)) yield x }\n\nconst result = map(\n  filter(range(100), n => n % 2 === 0),\n  n => n * n\n)   \u002F\u002F nothing computed until consumed\n```\n\nEach stage pulls one value at a time, so a pipeline over an infinite source\nstill works.\n",{"id":2520,"difficulty":84,"q":2521,"a":2522},"generator-this-binding","Can a generator be an arrow function?","No — there is **no arrow generator syntax**. Generators must be\n`function*` declarations\u002Fexpressions or `*method()` shorthand in\nobjects\u002Fclasses.\n\n```js\nconst g = function* () { yield 1 }      \u002F\u002F expression\nconst obj = { *gen() { yield 1 } }      \u002F\u002F method shorthand\n\u002F\u002F const bad = *() => {}                \u002F\u002F SyntaxError\n```\n\nAs object\u002Fclass methods, generators get `this` from the call site like any\nmethod, which is exactly why arrow generators aren't needed.\n",{"id":2524,"difficulty":63,"q":2525,"a":2526},"iterator-helpers","What are iterator helper methods?","Modern engines add lazy helper methods directly on iterators —\n`map`, `filter`, `take`, `drop`, `flatMap`, `reduce`, `toArray` — so you\nget array-like chaining without materializing arrays.\n\n```js\nfunction* naturals() { let n = 1; while (true) yield n++ }\nnaturals()\n  .filter(n => n % 2)\n  .map(n => n * n)\n  .take(3)\n  .toArray()           \u002F\u002F [1, 9, 25]  lazy, bounded by take\n```\n\nThey make working with infinite generators ergonomic; check target support\nas adoption is recent.\n",{"id":2528,"difficulty":63,"q":2529,"a":2530},"manual-vs-generator-iterator","Why prefer a generator over hand-writing an iterator object?","A generator manages all the protocol state for you — the `{ value, done }`\nshape, the `done` terminator, returning itself from `Symbol.iterator`, and\n`return()`\u002F`throw()` semantics. Hand-rolled iterators are verbose and\nerror-prone.\n\n```js\n\u002F\u002F generator: 3 lines vs a dozen for the manual next()\u002Fdone version\nfunction* range(s, e) { for (let i = s; i \u003C e; i++) yield i }\n```\n\nReserve manual iterators for cases needing unusual control over the\nprotocol; otherwise use a generator.\n",{"id":2532,"difficulty":63,"q":2533,"a":2534},"destructure-iterator","How do destructuring and spread interact with iterators?","Both consume an iterable via its iterator. Destructuring pulls only as many\nvalues as the pattern needs; spread drains it fully.\n\n```js\nfunction* g() { yield 1; yield 2; yield 3 }\nconst [a, b] = g()     \u002F\u002F pulls 2, iterator left at 3\nconst all = [...g()]   \u002F\u002F [1, 2, 3] — fully drained\n```\n\nBecause destructuring stops early, `const [first] = infinite()` is safe,\nbut `const [...rest] = infinite()` hangs.\n",{"id":2536,"difficulty":84,"q":2537,"a":2538},"generator-return-from-yieldstar","How do you capture the return value of a delegated generator?","`yield*` evaluates to the **return value** of the inner generator, letting\nyou build sub-results.\n\n```js\nfunction* inner() { yield 1; return 'done' }\nfunction* outer() {\n  const result = yield* inner()   \u002F\u002F result === 'done'\n  yield result\n}\n[...outer()]   \u002F\u002F [1, 'done']\n```\n\nThis is how generators compose computations: the yielded stream flows\nthrough while the return value bubbles back to the delegator.\n",{"id":2540,"difficulty":63,"q":2541,"a":2542},"when-not-to-use-generators","When should you avoid generators?","For small, fully-consumed collections, plain arrays\u002Farray methods are\nsimpler, faster to index, and easier to debug. Generators add overhead per\n`next()` call and can't be randomly accessed or reused.\n\n```js\n\u002F\u002F overkill — just use an array\nfunction* three() { yield 1; yield 2; yield 3 }\nconst arr = [1, 2, 3]   \u002F\u002F clearer here\n```\n\nReach for generators when you genuinely need laziness, infinite\u002Fstreaming\ndata, two-way communication, or memory-bounded processing.\n",{"description":61},"JavaScript generators and iterators interview questions — the iterator and iterable protocols, function* and yield, yield* delegation, lazy and infinite sequences, two-way communication and async generators.","javascript\u002Ffunctions\u002Fgenerators-iterators","Generators & Iterators","PjkAQb6KJH099D5oXrnCdLp3so5iSdXLlO3hoWit9iw",{"id":2549,"title":2550,"body":2551,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":2555,"navigation":66,"order":31,"path":2556,"questions":2557,"related":207,"seo":2681,"seoDescription":2682,"stem":2683,"subtopic":2684,"topic":2276,"topicSlug":2277,"updated":214,"__hash__":2685},"qa\u002Fjavascript\u002Ffunctions\u002Fhigher-order-functions.md","Higher Order Functions",{"type":58,"value":2552,"toc":2553},[],{"title":61,"searchDepth":22,"depth":22,"links":2554},[],{},"\u002Fjavascript\u002Ffunctions\u002Fhigher-order-functions",[2558,2562,2566,2570,2574,2578,2582,2586,2590,2593,2597,2601,2605,2609,2613,2617,2621,2625,2629,2633,2637,2641,2645,2649,2653,2657,2661,2665,2669,2673,2677],{"id":2559,"difficulty":71,"q":2560,"a":2561},"what-is-hof","What is a higher-order function?","A **higher-order function (HOF)** is a function that does at least one of two\nthings: **takes one or more functions as arguments**, or **returns a\nfunction**. Any function that only deals with plain values is *first-order*.\n\n```js\n\u002F\u002F takes a function (callback)\n[1, 2, 3].map(n => n * 2)              \u002F\u002F map is a HOF\n\n\u002F\u002F returns a function\nconst multiplier = factor => n => n * factor  \u002F\u002F HOF returning a HOF\nconst double = multiplier(2)\ndouble(5) \u002F\u002F 10\n```\n\nHOFs are possible because functions in JavaScript are **first-class values** —\nthey can be stored, passed, and returned like any other value. They are the\nbackbone of functional-style JS and enable reuse without copy-pasting logic.\n",{"id":2563,"difficulty":71,"q":2564,"a":2565},"what-is-callback","What is a callback function?","A **callback** is a function passed into another function so it can be\n**called back later** — either synchronously (now) or asynchronously (later).\n\n```js\n\u002F\u002F synchronous callback\n[1, 2, 3].forEach(n => console.log(n))   \u002F\u002F called once per element, now\n\n\u002F\u002F asynchronous callback\nsetTimeout(() => console.log('later'), 0) \u002F\u002F called after the timer fires\n```\n\nThe function receiving the callback decides **when** and **with what\narguments** to invoke it. A common gotcha: a synchronous-looking API may call\nthe callback asynchronously, so don't assume code after the call has the\ncallback's results yet.\n",{"id":2567,"difficulty":71,"q":2568,"a":2569},"map-as-hof","How is Array.prototype.map a higher-order function?","`map` is a HOF because it **accepts a function** and applies it to every\nelement, returning a **new array** of the results. It abstracts the loop.\n\n```js\nconst nums = [1, 2, 3]\nconst squared = nums.map(n => n * n)   \u002F\u002F [1, 4, 9]\n\u002F\u002F nums is unchanged — map does not mutate\n```\n\nThe callback receives `(element, index, array)`. **Pitfall:** `map` is for\ntransforming into a new array — if you only need side effects (logging,\npushing to the DOM) use `forEach` instead, otherwise you allocate an array of\n`undefined` you never use.\n",{"id":2571,"difficulty":71,"q":2572,"a":2573},"filter-as-hof","What does Array.prototype.filter do and why is it a HOF?","`filter` is a HOF that takes a **predicate** (a function returning a boolean)\nand returns a **new array** containing only the elements for which the\npredicate is truthy.\n\n```js\nconst nums = [1, 2, 3, 4]\nconst evens = nums.filter(n => n % 2 === 0)  \u002F\u002F [2, 4]\n```\n\nThe result's **truthiness** is what matters, not strict `true`. **Pitfall:**\nreturning a non-boolean accidentally — e.g. `filter(n => n.id)` keeps elements\nwith truthy `id`, which silently drops items whose id is `0` or `''`.\n",{"id":2575,"difficulty":63,"q":2576,"a":2577},"reduce-as-hof","Explain reduce as a higher-order function.","`reduce` is the most general array HOF: it takes a **reducer function**\n`(accumulator, element) => newAccumulator` plus an initial value, and folds\nthe whole array down to a **single value** (which can itself be an array or\nobject).\n\n```js\nconst sum = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0)  \u002F\u002F 10\n\n\u002F\u002F map and filter can both be expressed via reduce\nconst doubled = [1, 2, 3].reduce((acc, n) => [...acc, n * 2], []) \u002F\u002F [2,4,6]\n```\n\n**Pitfall:** omitting the initial value. Without it, the first element becomes\nthe accumulator and iteration starts at index 1 — and `reduce` on an **empty\narray with no initial value throws** a TypeError.\n",{"id":2579,"difficulty":63,"q":2580,"a":2581},"pure-vs-callback","Why do HOFs like map\u002Ffilter\u002Freduce make code more reusable?","They **separate the iteration mechanism from the per-element logic**. The HOF\nowns the loop, bounds checking, and array allocation; you supply only the\nsmall piece that varies. This is the **template method** idea expressed with\nfunctions.\n\n```js\n\u002F\u002F imperative: loop boilerplate repeated everywhere\nconst out = []\nfor (let i = 0; i \u003C users.length; i++) out.push(users[i].name)\n\n\u002F\u002F declarative: intent is obvious, no boilerplate\nconst names = users.map(u => u.name)   \u002F\u002F\n```\n\nBecause the callback is just a value, you can name it, test it in isolation,\nand reuse it across many call sites — reducing duplication and bugs.\n",{"id":2583,"difficulty":63,"q":2584,"a":2585},"function-composition","What is function composition?","**Composition** combines small functions into a bigger one, where the output\nof each becomes the input of the next — `compose(f, g)(x) === f(g(x))`.\n\n```js\nconst compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x)\nconst pipe    = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x)\n\nconst clean = pipe(s => s.trim(), s => s.toLowerCase())\nclean('  HELLO ')  \u002F\u002F 'hello'   reads left-to-right\n```\n\n`compose` runs **right-to-left** (math convention); `pipe` runs\n**left-to-right** (reads like a pipeline). **Pitfall:** each function should\ntake and return a single value — composition breaks down with multi-arg\nfunctions unless you curry them first.\n",{"id":2587,"difficulty":63,"q":2588,"a":2589},"what-is-currying","What is currying?","**Currying** transforms a function of N arguments into N nested functions that\neach take **one argument** and return the next function until all args are\ncollected.\n\n```js\nconst add = a => b => c => a + b + c   \u002F\u002F curried\nadd(1)(2)(3)   \u002F\u002F 6\n\n\u002F\u002F vs the normal form\nconst addN = (a, b, c) => a + b + c\naddN(1, 2, 3)  \u002F\u002F 6\n```\n\nCurrying enables **partial application** and clean composition, because each\nstage returns a specialized function. **Pitfall:** deeply curried APIs hurt\nreadability and are harder to debug — reserve currying for cases where the\npartial-application benefit is real.\n",{"id":2190,"difficulty":63,"q":2591,"a":2592},"What is partial application and how does it differ from currying?","**Partial application** fixes *some* of a function's arguments now, producing a\nnew function that takes the *rest* later. **Currying** is stricter: it always\nbreaks a function into a chain of **one-argument** functions.\n\n```js\nconst greet = (greeting, name) => `${greeting}, ${name}!`\nconst hi = greet.bind(null, 'Hi')   \u002F\u002F partial application via bind\nhi('Sam')  \u002F\u002F 'Hi, Sam!'   greeting already fixed\n```\n\nSo every curried call is a partial application, but partial application can\nfix several arguments at once and isn't restricted to one-at-a-time. `bind` is\nthe built-in tool for it (ignoring the `this` argument here with `null`).\n",{"id":2594,"difficulty":84,"q":2595,"a":2596},"point-free-style","What is point-free (tacit) style?","**Point-free style** defines functions **without naming their arguments**,\nbuilding them by composing other functions instead. The \"point\" is the data\nargument you don't mention.\n\n```js\n\u002F\u002F pointed\nconst isOdd = n => n % 2 === 1\nconst countOdds = arr => arr.filter(isOdd).length\n\n\u002F\u002F point-free helper composed from smaller pieces\nconst prop = key => obj => obj[key]\nconst names = users.map(prop('name'))   \u002F\u002F no obj parameter named\n```\n\nIt can read very cleanly, but **pitfall:** taken too far it becomes cryptic\nand stack traces lose meaningful names. Use it where it genuinely clarifies.\n",{"id":2598,"difficulty":63,"q":2599,"a":2600},"what-is-memoization","What is memoization and how do you implement it with a HOF?","**Memoization** caches a pure function's results keyed by its arguments, so\nrepeated calls with the same input return instantly instead of recomputing.\nA HOF wraps the original function and keeps the cache in a **closure**.\n\n```js\nfunction memoize(fn) {\n  const cache = new Map()\n  return function (arg) {\n    if (cache.has(arg)) return cache.get(arg)   \u002F\u002F cache hit\n    const result = fn.call(this, arg)\n    cache.set(arg, result)\n    return result\n  }\n}\n```\n\n**Pitfall:** it only works for **pure** functions (same input -> same output)\nand the naive version keys on a single primitive arg — multi-arg or object\nkeys need a serialization strategy and risk unbounded memory growth.\n",{"id":2602,"difficulty":63,"q":2603,"a":2604},"debounce-as-hof","How would you implement debounce, and why is it a HOF?","**Debounce** returns a wrapped function that delays calling the original until\nactivity has **stopped for a quiet period**; each new call resets the timer.\nIt's a HOF: it takes a function and returns a closure holding the timer.\n\n```js\nfunction debounce(fn, wait) {\n  let timer\n  return function (...args) {\n    clearTimeout(timer)\n    timer = setTimeout(() => fn.apply(this, args), wait)   \u002F\u002F resets\n  }\n}\nconst onSearch = debounce(query => fetchResults(query), 300)\n```\n\nGreat for search-as-you-type or resize handlers. **Pitfall:** the wrapper must\nforward `this` and `args` with `apply`, or the debounced handler loses its\ncontext and the event arguments.\n",{"id":2606,"difficulty":63,"q":2607,"a":2608},"throttle-as-hof","What is throttle and how does it differ from debounce?","**Throttle** guarantees the function runs **at most once per interval**, no\nmatter how often it's called — useful for scroll or mousemove. **Debounce**\ninstead waits until calls *stop*. Both are HOFs returning a stateful closure.\n\n```js\nfunction throttle(fn, interval) {\n  let last = 0\n  return function (...args) {\n    const now = Date.now()\n    if (now - last >= interval) {        \u002F\u002F fire on leading edge\n      last = now\n      fn.apply(this, args)\n    }\n  }\n}\n```\n\n**Rule of thumb:** throttle for *steady sampling* during continuous events;\ndebounce for *\"do it once they're done\"* events.\n",{"id":2610,"difficulty":63,"q":2611,"a":2612},"once-hof","How do you implement a once() higher-order function?","`once` returns a wrapper that lets the underlying function run **only the\nfirst time**; later calls return the cached first result and skip execution.\nThe \"have I run yet\" flag and result live in a closure.\n\n```js\nfunction once(fn) {\n  let called = false, result\n  return function (...args) {\n    if (!called) {\n      called = true\n      result = fn.apply(this, args)   \u002F\u002F runs exactly once\n    }\n    return result\n  }\n}\nconst init = once(() => console.log('setup'))\ninit(); init()   \u002F\u002F logs 'setup' only once\n```\n\nHandy for idempotent initialization. **Pitfall:** the result is cached forever\n— if the first call threw, decide whether `called` should stay false to allow\na retry.\n",{"id":2614,"difficulty":63,"q":2615,"a":2616},"returning-functions","Why would a function return another function?","Returning a function lets you **pre-configure behavior now and defer\nexecution to later**, capturing the configuration in a closure. This is the\nmechanism behind factories, currying, and middleware.\n\n```js\nfunction makeTagger(tag) {\n  return content => `\u003C${tag}>${content}\u003C\u002F${tag}>`   \u002F\u002F remembers `tag`\n}\nconst h1 = makeTagger('h1')\nh1('Hello')   \u002F\u002F '\u003Ch1>Hello\u003C\u002Fh1>'   tag captured\n```\n\nThe returned function is **specialized** without you rewriting it. The key\nenabler is the closure: each returned function keeps its own copy of the\ncaptured configuration.\n",{"id":2618,"difficulty":63,"q":2619,"a":2620},"callbacks-sync-async","What's the difference between synchronous and asynchronous callbacks?","A **synchronous callback** runs to completion *before* the HOF returns (like\n`map`'s callback). An **asynchronous callback** is scheduled and runs *later*,\nafter the current call stack clears (like `setTimeout` or a fetch handler).\n\n```js\nconsole.log('A')\n[1].forEach(() => console.log('B'))     \u002F\u002F sync -> B before C\nsetTimeout(() => console.log('D'), 0)   \u002F\u002F async -> D last\nconsole.log('C')\n\u002F\u002F order: A, B, C, D\n```\n\n**Pitfall:** mixing them in one API (\"sometimes sync, sometimes async\") causes\nsubtle bugs — choose one contract. This is also why callback-based async code\nled to \"callback hell\" and motivated Promises.\n",{"id":2622,"difficulty":84,"q":2623,"a":2624},"map-parseint-gotcha","Why does ['1','2','3'].map(parseInt) not return [1, 2, 3]?","`map` calls the callback with **three** arguments — `(value, index, array)` —\nbut `parseInt(string, radix)` reads the **second** as a radix. So you actually\ncall `parseInt('1', 0)`, `parseInt('2', 1)`, `parseInt('3', 2)`.\n\n```js\n['1', '2', '3'].map(parseInt)\n\u002F\u002F parseInt('1', 0) -> 1   (radix 0 ignored -> base 10)\n\u002F\u002F parseInt('2', 1) -> NaN (radix 1 invalid)\n\u002F\u002F parseInt('3', 2) -> NaN ('3' not a binary digit)\n\u002F\u002F result: [1, NaN, NaN]\n```\n\n**Fix:** wrap it so only the value is passed:\n`['1','2','3'].map(s => parseInt(s, 10))` -> `[1, 2, 3]`. The lesson: be\ncareful passing a multi-arity built-in directly as a callback.\n",{"id":2626,"difficulty":84,"q":2627,"a":2628},"losing-this-method-ref","Why does passing a method reference as a callback often lose `this`?","Passing `obj.method` extracts the **function value alone** — the `obj`\nreceiver is *not* attached. When the HOF later calls it as a plain function,\n`this` is `undefined` (strict) or the global object.\n\n```js\nconst counter = {\n  count: 0,\n  inc() { this.count++ }\n}\n[1, 2].forEach(counter.inc)   \u002F\u002F `this` is not `counter`\n```\n\n**Fixes:** bind it — `forEach(counter.inc.bind(counter))` — or wrap in an\narrow that preserves the receiver — `forEach(() => counter.inc())`. The\nroot cause is that `this` is determined by **how** a function is called, not\nwhere it was defined.\n",{"id":2630,"difficulty":63,"q":2631,"a":2632},"composition-vs-chaining","How does method chaining relate to function composition?","**Method chaining** (`arr.filter(...).map(...).reduce(...)`) is composition\nwhere each step is a **method returning a chainable value**. Standalone\n**composition** (`pipe(f, g, h)`) works on free functions and any data type,\nnot just arrays.\n\n```js\n\u002F\u002F chaining\nconst total = orders.filter(o => o.paid).map(o => o.amount)\n                    .reduce((a, b) => a + b, 0)   \u002F\u002F reads top-to-bottom\n\n\u002F\u002F composition with free functions\nconst total2 = pipe(\n  os => os.filter(o => o.paid),\n  os => os.map(o => o.amount),\n  os => os.reduce((a, b) => a + b, 0)\n)(orders)\n```\n\nChaining is ergonomic when the methods exist; composition is more general and\ndecouples logic from the data's prototype. **Pitfall:** long chains over large\narrays create many intermediate arrays.\n",{"id":2634,"difficulty":63,"q":2635,"a":2636},"flatmap-hof","What does flatMap do and when is it useful?","`flatMap` is a HOF that **maps then flattens one level** in a single pass. It's\nequivalent to `arr.map(fn).flat()` but more efficient and expressive.\n\n```js\nconst sentences = ['hello world', 'foo bar']\nconst words = sentences.flatMap(s => s.split(' '))\n\u002F\u002F ['hello', 'world', 'foo', 'bar']   flattened\n\n\u002F\u002F also handy to map-and-filter: return [] to drop\n[1, 2, 3].flatMap(n => n % 2 ? [n] : [])  \u002F\u002F [1, 3]\n```\n\n**Pitfall:** it only flattens **one** level — deeply nested results need\n`flat(Infinity)` afterwards.\n",{"id":2638,"difficulty":71,"q":2639,"a":2640},"every-some-hof","How do every() and some() use callbacks?","Both are HOFs taking a **predicate**. `every` returns `true` only if the\npredicate passes for **all** elements; `some` returns `true` if **at least\none** passes. Both **short-circuit**.\n\n```js\n[2, 4, 6].every(n => n % 2 === 0)  \u002F\u002F true\n[1, 2, 3].some(n => n > 2)         \u002F\u002F true (stops at 3)\n```\n\n`every` stops at the first falsy result; `some` stops at the first truthy\nresult. **Edge case:** `[].every(...)` is `true` (vacuous truth) and\n`[].some(...)` is `false`.\n",{"id":2642,"difficulty":84,"q":2643,"a":2644},"bind-vs-arrow-callback","When wiring a callback, should you use bind or an arrow wrapper?","Both fix the receiver. `bind` creates a **new bound function once**, ideal when\nyou need a **stable reference** (e.g. to later `removeEventListener`). An arrow\nwrapper is created fresh each render\u002Fcall and is convenient for forwarding\nchanging arguments.\n\n```js\n\u002F\u002F stable, removable\nconst handler = this.onClick.bind(this)\nel.addEventListener('click', handler)\nel.removeEventListener('click', handler)   \u002F\u002F same reference\n\n\u002F\u002F arrow re-created each time -> cannot remove\nel.addEventListener('click', () => this.onClick())  \u002F\u002F no handle to remove\n```\n\n**Pitfall:** binding inside JSX\u002Frender or in a loop creates a new function\nevery time, which can defeat memoization and break listener removal.\n",{"id":2646,"difficulty":63,"q":2647,"a":2648},"identity-and-constant","What are identity and constant functions and why are they useful in HOF code?","`identity = x => x` returns its argument unchanged; `constant = x => () => x`\nreturns a function that always yields `x`. They are tiny **building blocks**\nthat make HOF pipelines uniform.\n\n```js\nconst identity = x => x\n\u002F\u002F filter out falsy values with no custom predicate\n['a', '', 'b', null].filter(identity)   \u002F\u002F ['a', 'b']\n\nconst always5 = (() => () => 5)()\n[1, 2, 3].map(always5)   \u002F\u002F [5, 5, 5]\n```\n\nThey shine as **default callbacks** (e.g. a sort key defaulting to identity)\nand in composition where you need a no-op transform.\n",{"id":2650,"difficulty":84,"q":2651,"a":2652},"compose-data-last","Why do functional libraries favor \"data-last\" argument order?","**Data-last** means the data parameter comes *last*, so the earlier\nconfiguration args can be **partially applied** to build reusable, composable\nfunctions. The data flows in only at the end of a pipeline.\n\n```js\nconst map = fn => arr => arr.map(fn)        \u002F\u002F data (arr) last\nconst filter = pred => arr => arr.filter(pred)\n\nconst process = pipe(filter(x => x > 0), map(x => x * 2))\nprocess([-1, 2, 3])   \u002F\u002F [4, 6]   data supplied last\n```\n\nNative array methods are **data-first** (`arr.map(fn)`), which is why you\noften wrap them. The trade-off: data-last composes beautifully but reads\nbackwards from the method style most JS developers know.\n",{"id":2654,"difficulty":63,"q":2655,"a":2656},"callback-error-handling","What is the \"error-first\" callback convention?","The Node-style **error-first callback** convention passes the error as the\n**first argument** and the result(s) afterward: `callback(err, data)`. If\n`err` is truthy, something failed.\n\n```js\nfs.readFile('x.txt', (err, data) => {\n  if (err) return handle(err)   \u002F\u002F check error first\n  use(data)\n})\n```\n\n**Pitfall:** forgetting to `return` after handling the error lets the success\npath run with `undefined` data. This convention predates Promises, which\nlargely replaced it with `.then\u002F.catch` and `async\u002Fawait`.\n",{"id":2658,"difficulty":63,"q":2659,"a":2660},"hof-this-arg","How do you set `this` for an array HOF callback without binding?","Many array HOFs accept an optional **`thisArg`** as their last parameter. When\nprovided (and the callback is a regular function, not an arrow), `this` inside\nthe callback is set to it.\n\n```js\nconst ctx = { factor: 3 }\n[1, 2, 3].map(function (n) { return n * this.factor }, ctx)  \u002F\u002F [3, 6, 9]\n```\n\n**Pitfall:** `thisArg` is **ignored by arrow callbacks**, because arrows take\n`this` lexically. Most modern code just uses an arrow that closes over the\nvalue instead of relying on `thisArg`.\n",{"id":2662,"difficulty":84,"q":2663,"a":2664},"composing-async","How do you compose asynchronous functions?","Plain `compose`\u002F`pipe` assume synchronous functions. For async, each step\nreturns a Promise, so you **await between stages** — often by reducing over an\ninitial resolved Promise.\n\n```js\nconst pipeAsync = (...fns) => x =>\n  fns.reduce((acc, fn) => acc.then(fn), Promise.resolve(x))\n\nconst run = pipeAsync(fetchUser, u => fetchPosts(u.id), posts => posts.length)\nrun(42).then(console.log)   \u002F\u002F each step awaits the previous\n```\n\n**Pitfall:** mixing sync and async functions in one pipe is fine here because\n`then` auto-wraps non-Promise returns — but an unhandled rejection in any\nstage rejects the whole chain, so attach a `.catch`.\n",{"id":2666,"difficulty":84,"q":2667,"a":2668},"curry-auto","How would you write a generic curry() helper?","A generic `curry` collects arguments until it has received as many as the\nfunction's **declared arity** (`fn.length`), then invokes it. Until then it\nreturns a function that accumulates more args.\n\n```js\nfunction curry(fn) {\n  return function curried(...args) {\n    if (args.length >= fn.length) return fn.apply(this, args)\n    return (...next) => curried.apply(this, [...args, ...next])   \u002F\u002F\n  }\n}\nconst add = curry((a, b, c) => a + b + c)\nadd(1)(2)(3)   \u002F\u002F 6\nadd(1, 2)(3)   \u002F\u002F 6   — flexible grouping\n```\n\n**Pitfall:** it relies on `fn.length`, which **excludes** rest params and\nparameters with defaults — so currying variadic functions doesn't work without\npassing an explicit arity.\n",{"id":2670,"difficulty":84,"q":2671,"a":2672},"hof-reuse-vs-inheritance","How do HOFs offer an alternative to class inheritance for sharing behavior?","Instead of subclassing to share behavior, you can **wrap functions with HOFs**\n(decorators) to add cross-cutting concerns like logging, caching, or retries —\n**composition over inheritance**.\n\n```js\nconst withLogging = fn => (...args) => {\n  console.log('call', fn.name, args)\n  return fn(...args)\n}\nconst withRetry = fn => async (...args) => {\n  try { return await fn(...args) } catch { return fn(...args) }\n}\nconst robustFetch = withLogging(withRetry(fetchData))   \u002F\u002F stacked\n```\n\nEach concern is an independent, testable HOF you can stack in any order. This\navoids deep inheritance hierarchies and the fragile base-class problem.\n",{"id":2674,"difficulty":63,"q":2675,"a":2676},"tap-debugging","What is a tap() function and how does it help debug pipelines?","`tap` runs a **side effect** (like logging) on a value and then **returns the\nvalue unchanged**, so you can drop it into a composition without altering the\ndata flow.\n\n```js\nconst tap = fn => x => { fn(x); return x }\n\nconst result = pipe(\n  x => x + 1,\n  tap(x => console.log('after +1:', x)),   \u002F\u002F peeks, passes through\n  x => x * 2\n)(5)   \u002F\u002F logs 6, result 12\n```\n\nIt's the functional equivalent of a breakpoint. **Pitfall:** because it's for\nside effects, don't accidentally `return fn(x)` — that would replace the value\nand corrupt the pipeline.\n",{"id":2678,"difficulty":84,"q":2679,"a":2680},"avoid-shared-mutable-closure","What bug can a HOF cause by sharing mutable state across returned functions?","If a HOF closes over a **shared mutable variable** and returns functions that\nall reference it, they can interfere with each other — the classic loop-closure\ntrap.\n\n```js\nfunction makeHandlers() {\n  const fns = []\n  for (var i = 0; i \u003C 3; i++) fns.push(() => i)   \u002F\u002F all see final i\n  return fns\n}\nmakeHandlers().map(f => f())   \u002F\u002F [3, 3, 3]\n```\n\n**Fix:** use `let` (per-iteration binding) so each closure captures its own\n`i` -> `[0, 1, 2]`. The deeper lesson: when a HOF returns multiple closures,\nbe deliberate about whether they should **share** or **own** their captured\nstate.\n",{"description":61},"JavaScript higher-order function interview questions — callbacks, map\u002Ffilter\u002F reduce, composition, currying, partial application, memoization, debounce and throttle, plus classic callback pitfalls.","javascript\u002Ffunctions\u002Fhigher-order-functions","Higher-Order Functions","gajpsA9HuJ91gZ5frBbNlC6sHDnB7KjdH7Q19PqI4FY",{"id":2687,"title":2688,"body":2689,"description":61,"difficulty":84,"extension":64,"framework":11,"frameworkSlug":9,"meta":2693,"navigation":66,"order":22,"path":2694,"questions":2695,"related":207,"seo":2827,"seoDescription":2828,"stem":2829,"subtopic":2830,"topic":2276,"topicSlug":2277,"updated":1525,"__hash__":2831},"qa\u002Fjavascript\u002Ffunctions\u002Fthis-keyword.md","This Keyword",{"type":58,"value":2690,"toc":2691},[],{"title":61,"searchDepth":22,"depth":22,"links":2692},[],{},"\u002Fjavascript\u002Ffunctions\u002Fthis-keyword",[2696,2700,2704,2708,2712,2716,2720,2724,2728,2732,2736,2740,2744,2748,2752,2756,2760,2764,2768,2772,2776,2780,2783,2787,2791,2795,2799,2803,2807,2811,2815,2819,2823],{"id":2697,"difficulty":63,"q":2698,"a":2699},"what-is-this","How is the value of `this` determined?","The single most important idea: in a regular function `this` is decided by\n**how the function is *called*, not where it's defined**. There are four\nbinding rules, in order of precedence:\n\n1. **`new` binding** — `new Fn()` -> `this` is the brand-new instance.\n2. **Explicit binding** — `fn.call(obj)`, `fn.apply(obj)`, `fn.bind(obj)` ->\n   `this` is the object you pass.\n3. **Implicit binding** — `obj.fn()` -> `this` is `obj` (the thing left of the\n   dot).\n4. **Default binding** — a plain `fn()` -> `this` is `undefined` in strict mode,\n   or the global object (`window`\u002F`globalThis`) in sloppy mode.\n\n```js\nfunction who() { return this }\nconst obj = { who }\nobj.who()            \u002F\u002F obj      (implicit)\nwho.call('hi')       \u002F\u002F 'hi'     (explicit)\nnew who()            \u002F\u002F {}       (new instance)\nwho()                \u002F\u002F undefined in strict mode\n```\n\nArrow functions are the exception — they ignore all four rules and inherit\n`this` lexically (next question).\n",{"id":2701,"difficulty":63,"q":2702,"a":2703},"arrow-this","How does `this` work in arrow functions?","Arrow functions **don't have their own `this`**. They capture it\n**lexically** — from the enclosing scope at the moment they're *defined* — and\nthat binding can never be changed (even `call`\u002F`apply`\u002F`bind` can't reassign\nit). This makes them perfect for callbacks where you want to keep the\nsurrounding object's `this`.\n\n```js\nclass Timer {\n  seconds = 0\n  start() {\n    \u002F\u002F arrow inherits `start`'s `this` (the Timer instance)\n    setInterval(() => this.seconds++, 1000)\n\n    \u002F\u002F a regular function here would be called by the timer with\n    \u002F\u002F `this` === undefined, so `this.seconds` would throw\n  }\n}\n```\n\nThe flip side: because they lack their own `this`, arrows are a poor choice for\n**object methods that need to reference the object** (`this` would point to the\nouter scope, not the object) and they **cannot be used as constructors**.\n",{"id":2705,"difficulty":63,"q":2706,"a":2707},"call-apply-bind","What is the difference between call, apply and bind?","All three let you **explicitly set `this`**; they differ in *when* they invoke\nand *how* they take arguments:\n\n- `fn.call(thisArg, a, b)` — invokes **immediately**, arguments passed\n  **individually**.\n- `fn.apply(thisArg, [a, b])` — invokes **immediately**, arguments passed as an\n  **array**.\n- `fn.bind(thisArg, a)` — does **not** invoke; returns a **new function** with\n  `this` (and any given args) **permanently** locked in.\n\n```js\nfunction greet(greeting, mark) {\n  return `${greeting}, ${this.name}${mark}`\n}\nconst user = { name: 'Ada' }\n\ngreet.call(user, 'Hi', '!')      \u002F\u002F 'Hi, Ada!'   (args listed)\ngreet.apply(user, ['Hi', '!'])   \u002F\u002F 'Hi, Ada!'   (args in array)\nconst greetAda = greet.bind(user) \u002F\u002F returns a function\ngreetAda('Hey', '.')             \u002F\u002F 'Hey, Ada.'\n```\n\nMemory aid: **A**pply = **A**rray; **bind** = \"remember for later.\" `bind` is\nthe usual fix for passing a method as a callback without losing its receiver.\n",{"id":2709,"difficulty":84,"q":2710,"a":2711},"lost-this","Why does `this` become undefined when passing a method as a callback?","Because `this` is set at **call time** by the *call site*, and passing a method\nsomewhere else detaches it from its object. `setTimeout(obj.fn)` only copies\nthe **function** — the `obj.` context is lost, so when the timer later calls it\nas a plain function, `this` is `undefined` (strict) \u002F global (sloppy).\n\n```js\nconst counter = {\n  count: 0,\n  inc() { this.count++ },\n}\n\nsetTimeout(counter.inc, 100)        \u002F\u002F `this` is not `counter` -> throws\u002FNaN\n\nsetTimeout(counter.inc.bind(counter), 100)  \u002F\u002F bind the receiver\nsetTimeout(() => counter.inc(), 100)        \u002F\u002F arrow calls it ON counter\n```\n\nThis is exactly why React class components had to do\n`this.handleClick = this.handleClick.bind(this)` in the constructor — or use\nclass arrow-field methods, which sidestep the problem.\n",{"id":2713,"difficulty":63,"q":2714,"a":2715},"new-binding","What does `this` refer to inside a constructor function?","When you call a function with `new`, JavaScript does four things: (1) creates a\nfresh empty object, (2) sets that object's prototype to the constructor's\n`.prototype`, (3) binds `this` to the new object inside the call, and (4)\nreturns that object automatically — **unless** the constructor explicitly\nreturns its own (non-primitive) object.\n\n```js\nfunction User(name) {\n  this.name = name      \u002F\u002F `this` is the new instance\n  \u002F\u002F no return needed — the instance is returned for you\n}\nconst u = new User('Ada')\nu.name \u002F\u002F 'Ada'\n\nfunction Weird() {\n  this.a = 1\n  return { b: 2 } \u002F\u002F returning an object overrides the default `this`\n}\nnew Weird() \u002F\u002F { b: 2 }  (the `this.a = 1` is discarded)\n```\n\nForgetting `new` is a classic bug: calling `User('Ada')` plainly runs default\nbinding, so `this` is the global object and you accidentally create a global\n`name`.\n",{"id":2717,"difficulty":63,"q":2718,"a":2719},"this-strict","How does strict mode change `this` in a plain function call?","In **sloppy (non-strict) mode**, a plain function call defaults `this` to the\n**global object** (`window` \u002F `globalThis`). In **strict mode** — and inside ES\nmodules and class bodies, which are *always* strict — that same call leaves\n`this` as **`undefined`**.\n\n```js\nfunction show() { return this }\n\n\u002F\u002F sloppy mode\nshow() \u002F\u002F the global object\n\n\u002F\u002F strict mode\n'use strict'\nshow() \u002F\u002F undefined\n```\n\nThis is a feature, not a nuisance: with `undefined` you get a loud\n`TypeError` the moment you accidentally rely on default binding\n(`Cannot read properties of undefined`), instead of silently leaking\nproperties onto the global object. It surfaces \"I forgot to bind `this`\" bugs\nimmediately.\n",{"id":2721,"difficulty":84,"q":2722,"a":2723},"this-precedence","What is the precedence order of the this binding rules?","When multiple rules could apply, they resolve in this order (highest first):\n\n1. **`new` binding** — `new Fn()` wins over everything.\n2. **Explicit binding** — `call`\u002F`apply`\u002F`bind`.\n3. **Implicit binding** — `obj.method()`.\n4. **Default binding** — plain `fn()` -> `undefined`\u002Fglobal.\n\n```js\nfunction f() { return this.id }\nconst obj = { id: 1, f }\nconst bound = f.bind({ id: 2 })\nobj.f()            \u002F\u002F 1 (implicit)\nbound()            \u002F\u002F 2 (explicit beats implicit)\nnew bound().id     \u002F\u002F undefined-> new beats bind (this is the new instance)\n```\n\nArrow functions sit outside this hierarchy entirely — they ignore all four rules\nand inherit `this` lexically.\n",{"id":2725,"difficulty":63,"q":2726,"a":2727},"this-event-listener","What is this inside a DOM event listener?","In a **regular function** listener, `this` is the **element** the handler is\nattached to (the `currentTarget`). In an **arrow function**, `this` is inherited\nfrom the surrounding scope instead.\n\n```js\nbutton.addEventListener('click', function () {\n  this \u002F\u002F the button element\n})\nbutton.addEventListener('click', () => {\n  this \u002F\u002F whatever `this` was outside (NOT the button)\n})\n```\n\nSo use a regular function when you want `this` to be the element; use an arrow\n(and `e.currentTarget`) when you need the outer `this`. This trips people up when\nconverting handlers to arrows.\n",{"id":2729,"difficulty":63,"q":2730,"a":2731},"this-foreach","How do you control this inside forEach and similar methods?","`forEach`, `map`, `filter`, etc. accept an optional **`thisArg`** second argument\nthat sets `this` for the callback. Alternatively, use an arrow function that\ninherits `this` lexically.\n\n```js\nconst obj = {\n  prefix: '>',\n  log(arr) {\n    arr.forEach(function (x) { console.log(this.prefix, x) }, this) \u002F\u002F thisArg\n    arr.forEach(x => console.log(this.prefix, x))                   \u002F\u002F arrow\n  },\n}\n```\n\nWithout the `thisArg` (or an arrow), a regular callback's `this` would be\n`undefined`\u002Fglobal, and `this.prefix` would throw. Arrows are the modern,\npreferred fix.\n",{"id":2733,"difficulty":63,"q":2734,"a":2735},"method-borrowing","What is method borrowing?","Method borrowing uses `call`\u002F`apply` to invoke a method from one object **on**\nanother object that doesn't have it — by explicitly setting `this`. Classic for\narray-like objects.\n\n```js\nfunction sum() {\n  \u002F\u002F `arguments` is array-like, not a real array\n  return Array.prototype.reduce.call(arguments, (a, b) => a + b, 0)\n}\nsum(1, 2, 3) \u002F\u002F 6\n\nconst arrayLike = { 0: 'a', 1: 'b', length: 2 }\nArray.prototype.join.call(arrayLike, '-') \u002F\u002F 'a-b'\n```\n\nYou \"borrow\" `Array.prototype` methods for array-likes (`arguments`, NodeLists).\nModern code often uses `Array.from`\u002Fspread instead, but borrowing shows how `this`\ndecouples a method from its object.\n",{"id":2737,"difficulty":63,"q":2738,"a":2739},"bind-partial","How does bind enable partial application?","Beyond setting `this`, `bind` lets you **pre-fill leading arguments**, returning a\nfunction that takes the rest — partial application.\n\n```js\nfunction multiply(a, b) { return a * b }\nconst double = multiply.bind(null, 2) \u002F\u002F a is fixed to 2\ndouble(5) \u002F\u002F 10\n\nconst log = console.log.bind(console, '[APP]')\nlog('started') \u002F\u002F [APP] started\n```\n\nThe `null` thisArg is common when you only care about pre-binding arguments, not\n`this`. The bound arguments are remembered via the bound function's internal\nstate.\n",{"id":2741,"difficulty":84,"q":2742,"a":2743},"new-overrides-bind","Does the new operator override a bound this?","Yes. `new` takes precedence over `bind` — when you call `new` on a bound function,\n`this` is the **new instance**, not the value you bound. (Pre-bound **arguments**\nare still applied, though.)\n\n```js\nfunction Point(x, y) { this.x = x; this.y = y }\nconst BoundPoint = Point.bind({ ignored: true }, 10)\nconst p = new BoundPoint(20)\np.x \u002F\u002F 10 (bound arg kept)\np.y \u002F\u002F 20\n\u002F\u002F p is a fresh instance; the bound { ignored: true } this was ignored\n```\n\nThis is the one case where `bind`'s \"permanent\" `this` is overridden, reflecting\nthat `new` is the highest-precedence binding rule.\n",{"id":2745,"difficulty":63,"q":2746,"a":2747},"this-callback-loss","Why is this lost when passing an object method as a callback?","Passing `obj.method` as a callback copies only the **function**, detaching it from\n`obj`. When the receiver later calls it as a plain function, implicit binding is\ngone, so `this` is `undefined`\u002Fglobal.\n\n```js\nconst user = { name: 'Ada', greet() { return this.name } }\nconst fn = user.greet\nfn()                       \u002F\u002F undefined — detached\nsetTimeout(user.greet, 0)  \u002F\u002F also detached\n\nsetTimeout(() => user.greet(), 0)     \u002F\u002F called ON user\nsetTimeout(user.greet.bind(user), 0)  \u002F\u002F bound\n```\n\nThe fix is to preserve the receiver via an arrow wrapper or `bind`.\n",{"id":2749,"difficulty":63,"q":2750,"a":2751},"this-promise","What is this inside a promise .then callback?","A regular-function `.then` callback is invoked by the promise machinery with no\nreceiver, so `this` is `undefined` (strict) \u002F global. An **arrow** `.then`\ncallback inherits `this` from the enclosing scope.\n\n```js\nclass Loader {\n  url = '\u002Fapi'\n  load() {\n    fetch(this.url)\n      .then(r => r.json())\n      .then(data => this.handle(data)) \u002F\u002F arrow keeps `this` = the Loader\n  }\n  handle(data) {}\n}\n```\n\nUsing arrows in `.then` chains is the norm precisely so `this` stays the\nsurrounding object. A regular function there would lose it.\n",{"id":2753,"difficulty":63,"q":2754,"a":2755},"this-in-class","How does this behave in class methods?","Inside a class method, `this` refers to the **instance** when called as\n`instance.method()`. But class bodies are **always strict**, so an extracted\nmethod called plainly has `this === undefined` (not the global object).\n\n```js\nclass Counter {\n  count = 0\n  inc() { this.count++ }\n}\nconst c = new Counter()\nconst f = c.inc\nf() \u002F\u002F TypeError: Cannot read properties of undefined\n\n\u002F\u002F fix with a class field arrow method:\nclass Counter2 { count = 0; inc = () => this.count++ }\n```\n\nArrow **class fields** bind `this` to the instance permanently, which is why\nthey're popular for handlers.\n",{"id":2757,"difficulty":63,"q":2758,"a":2759},"this-module-top","What is this at the top level of a module or script?","It depends on the context. In a **classic script** (non-strict), top-level `this`\nis the **global object** (`window`). In an **ES module**, top-level `this` is\n**`undefined`** (modules are always strict and have their own scope). In **Node\nCommonScript** modules, it's `module.exports`.\n\n```js\n\u002F\u002F classic \u003Cscript>:  this === window\n\u002F\u002F ES module (type=\"module\" \u002F .mjs):  this === undefined\n\u002F\u002F Node CommonScript module:  this === module.exports\n```\n\nUse **`globalThis`** to reliably reference the global object across all of these\nenvironments.\n",{"id":2761,"difficulty":84,"q":2762,"a":2763},"arrow-method-pitfall","Why shouldn't you use an arrow function as an object method?","An arrow method captures `this` from the **enclosing scope at definition time** —\nwhich for an object literal is the surrounding scope, **not the object**. So\n`this` won't be the object you expect.\n\n```js\nconst obj = {\n  name: 'Ada',\n  greet: () => `Hi, ${this.name}`, \u002F\u002F `this` is the outer scope, not obj\n}\nobj.greet() \u002F\u002F 'Hi, undefined'\n\nconst obj2 = { name: 'Ada', greet() { return `Hi, ${this.name}` } }\nobj2.greet() \u002F\u002F 'Hi, Ada'\n```\n\nUse **method shorthand** (a regular function) for object methods that reference\n`this`. Reserve arrows for callbacks where you *want* the outer `this`.\n",{"id":2765,"difficulty":71,"q":2766,"a":2767},"globalthis","What is globalThis?","`globalThis` (ES2020) is a standardized way to access the **global object** in any\nJavaScript environment — `window` in browsers, `self` in workers, `global` in\nNode — without environment checks.\n\n```js\nglobalThis.myGlobal = 42\n\u002F\u002F before globalThis you needed:\nconst g = typeof window !== 'undefined' ? window\n        : typeof global !== 'undefined' ? global : self\n```\n\nIt removes the brittle feature-detection people used to write. Relevant to `this`\nbecause default-bound `this` in sloppy mode *is* this global object.\n",{"id":2769,"difficulty":63,"q":2770,"a":2771},"this-destructuring","What happens to this when you destructure a method off an object?","Destructuring extracts the **function value** without its object, so calling it\nloses implicit binding — `this` becomes `undefined`\u002Fglobal, exactly like assigning\nthe method to a variable.\n\n```js\nconst { greet } = user\ngreet() \u002F\u002F `this` is not `user` -> likely a TypeError\n\n\u002F\u002F common real example: destructuring instance methods\nconst { increment } = counter\nincrement() \u002F\u002F detached\n```\n\nIf a method uses `this`, don't destructure it (or `bind` it first). This bites\npeople destructuring class instances or React class methods.\n",{"id":2773,"difficulty":63,"q":2774,"a":2775},"this-settimeout","What is this inside a setTimeout callback?","A regular-function `setTimeout` callback is invoked by the timer with no receiver,\nso `this` is the global object (sloppy) \u002F `undefined` (strict). An arrow callback\ninherits `this` from the surrounding scope.\n\n```js\nconst obj = {\n  value: 42,\n  start() {\n    setTimeout(function () { console.log(this.value) }, 100) \u002F\u002F undefined\u002Fglobal\n    setTimeout(() => console.log(this.value), 100)           \u002F\u002F 42 (arrow)\n  },\n}\n```\n\nThe arrow form (or `bind(this)`) is the standard way to keep the surrounding\nobject's `this` in timer callbacks.\n",{"id":2777,"difficulty":63,"q":2778,"a":2779},"this-getter","What is this inside a getter or setter?","In a getter\u002Fsetter, `this` is the **object the property is accessed on** — just\nlike a regular method — so you can compute the value from other properties of that\nobject.\n\n```js\nconst person = {\n  first: 'Ada', last: 'Lovelace',\n  get fullName() { return `${this.first} ${this.last}` },\n  set fullName(v) { [this.first, this.last] = v.split(' ') },\n}\nperson.fullName        \u002F\u002F 'Ada Lovelace'\nperson.fullName = 'Grace Hopper'\n```\n\nDon't define a getter\u002Fsetter with an arrow — it wouldn't bind `this` to the\nobject. Use regular `get`\u002F`set` syntax.\n",{"id":2781,"difficulty":63,"q":2040,"a":2782},"this-static","In a `static` method, `this` refers to the **class itself** (the constructor\nfunction), not an instance — so you can access other static members.\n\n```js\nclass MathUtil {\n  static PI = 3.14159\n  static circleArea(r) { return this.PI * r * r } \u002F\u002F this === MathUtil\n}\nMathUtil.circleArea(2) \u002F\u002F 12.566...\n```\n\nBecause `this` is the class, static methods can call sibling statics via `this`,\nand `this` even respects subclasses (if called as `SubClass.method()`, `this` is\n`SubClass`).\n",{"id":2784,"difficulty":71,"q":2785,"a":2786},"self-pattern","What is the \"const self = this\" pattern?","Before arrow functions, you'd capture the outer `this` into an ordinary variable\n(`self`, `that`, or `_this`) so nested regular functions could reference it via\nthe closure, sidestepping their own `this`.\n\n```js\nfunction Timer() {\n  const self = this\n  this.seconds = 0\n  setInterval(function () {\n    self.seconds++ \u002F\u002F uses the captured outer `this`\n  }, 1000)\n}\n```\n\nArrow functions made this obsolete — `setInterval(() => this.seconds++, 1000)`\ndoes the same thing — but you'll still see `self`\u002F`that` in older codebases and\ntranspiled output.\n",{"id":2788,"difficulty":63,"q":2789,"a":2790},"this-react-class","Why do React class components need to bind this?","A class method passed as an event handler (`onClick={this.handleClick}`) is\ndetached from the instance, so `this` is `undefined` when React calls it. Class\nbodies are strict, so you get a `TypeError` on `this.setState`.\n\n```js\nclass Btn extends React.Component {\n  constructor(p) { super(p); this.handleClick = this.handleClick.bind(this) }\n  handleClick() { this.setState(...) } \u002F\u002F needs bound `this`\n  \u002F\u002F or: handleClick = () => this.setState(...)  \u002F\u002F arrow class field\n}\n```\n\nFixes: bind in the constructor, or use an **arrow class field** (which captures\nthe instance `this`). Function components with hooks avoid the issue entirely.\n",{"id":2792,"difficulty":63,"q":2793,"a":2794},"fluent-this","How does returning this enable method chaining?","If each method **returns `this`** (the instance), you can chain calls together —\nthe basis of fluent\u002Fbuilder APIs.\n\n```js\nclass Query {\n  parts = []\n  where(c) { this.parts.push(c); return this }\n  order(o) { this.parts.push(o); return this }\n  build() { return this.parts.join(' ') }\n}\nnew Query().where('a=1').order('b').build()\n```\n\nEach call resolves `this` to the same instance (implicit binding) and hands it\nback, so the next call operates on the same object. Returning `this` is the key.\n",{"id":2796,"difficulty":84,"q":2797,"a":2798},"this-nested-regular","What is this in a regular function nested inside a method?","A regular function defined **inside** a method does **not** inherit the method's\n`this`. When called plainly, it gets its own default binding (`undefined`\u002Fglobal),\nwhich is a frequent bug.\n\n```js\nconst obj = {\n  items: [1, 2],\n  process() {\n    this.items.forEach(function (x) {\n      console.log(this.items) \u002F\u002F `this` is not obj here\n    })\n  },\n}\n```\n\nFixes: arrow function (inherits `this`), `thisArg`, or `const self = this`. The\nnested **regular** function losing `this` is the classic gotcha arrows solved.\n",{"id":2800,"difficulty":63,"q":2801,"a":2802},"this-apply-spread","What is the difference between apply and the spread operator for arguments?","`apply` was historically used to pass an array of arguments **and** set `this`.\nThe **spread** operator (`...`) spreads an array into arguments without dealing\nwith `this`, so it's cleaner when you only need to forward arguments.\n\n```js\nconst nums = [5, 6, 2, 3]\nMath.max.apply(null, nums) \u002F\u002F 6 (old way — null thisArg)\nMath.max(...nums)          \u002F\u002F 6 (modern, no thisArg needed)\n```\n\nUse spread when `this` is irrelevant (most cases); keep `apply` when you must set\n`this` **and** pass an arguments array together.\n",{"id":2804,"difficulty":63,"q":2805,"a":2806},"this-iife","What is this inside an IIFE?","An IIFE is invoked as a **plain function call**, so default binding applies:\n`this` is the **global object** in sloppy mode and **`undefined`** in strict mode.\n\n```js\n(function () {\n  console.log(this) \u002F\u002F window (sloppy) \u002F undefined (strict)\n})()\n\n(function () {\n  'use strict'\n  console.log(this) \u002F\u002F undefined\n})()\n```\n\nThat's why old module-pattern IIFEs sometimes passed `this`\u002F`window` in\nexplicitly: `(function (global) { ... })(this)`.\n",{"id":2808,"difficulty":71,"q":2809,"a":2810},"this-object-literal","What is this in object method shorthand?","Method shorthand (`method() {}`) creates a regular function, so `this` is the\nobject the method is called on — standard implicit binding.\n\n```js\nconst calculator = {\n  value: 0,\n  add(n) { this.value += n; return this },\n}\ncalculator.add(5).add(3) \u002F\u002F this is calculator throughout -> value 8\n```\n\nShorthand is the right way to define methods that use `this`. (Contrast with an\narrow property, which would NOT bind to the object.)\n",{"id":2812,"difficulty":84,"q":2813,"a":2814},"this-rebind-bound","Can you rebind an already-bound function?","No. Once a function is bound with `bind`, its `this` is **permanently fixed** —\ncalling `bind` again, or `call`\u002F`apply` with a different `this`, **cannot change**\nit.\n\n```js\nfunction f() { return this.id }\nconst bound = f.bind({ id: 1 })\nbound.call({ id: 2 }) \u002F\u002F 1 — the rebind is ignored\nbound.bind({ id: 3 })() \u002F\u002F 1 — still 1\n```\n\nThe first `bind` wins. This \"hard binding\" is sometimes the goal (locking `this`),\nbut it surprises people expecting `call` to override it.\n",{"id":2816,"difficulty":84,"q":2817,"a":2818},"this-call-primitive","What happens when you pass a primitive as thisArg in sloppy mode?","In **sloppy mode**, a primitive `thisArg` passed to `call`\u002F`apply`\u002F`bind` is\n**boxed** into its wrapper object (`Number`, `String`, `Boolean`), and `null`\u002F\n`undefined` become the **global object**. In **strict mode**, `this` is left\nexactly as passed.\n\n```js\nfunction f() { return this }\n\u002F\u002F sloppy mode:\nf.call(5)         \u002F\u002F Number {5}  (boxed)\nf.call(null)      \u002F\u002F global object\n\u002F\u002F strict mode:\nf.call(5)         \u002F\u002F 5 (primitive, unboxed)\nf.call(null)      \u002F\u002F null\n```\n\nStrict mode's \"leave `this` as-is\" behavior is more predictable, another reason\nmodern code runs strict by default.\n",{"id":2820,"difficulty":63,"q":2821,"a":2822},"arrow-no-arguments","Besides this, what else do arrow functions not have?","Arrow functions also lack their own **`arguments`** object, **`super`**, and\n**`new.target`**, and they **can't be used as constructors** (no `new`). Like\n`this`, `arguments` is inherited lexically from the enclosing function.\n\n```js\nfunction outer() {\n  const arrow = () => arguments[0] \u002F\u002F refers to outer's arguments\n  return arrow\n}\nouter(42)() \u002F\u002F 42\n\nconst Foo = () => {}\nnew Foo() \u002F\u002F TypeError: Foo is not a constructor\n```\n\nUse rest parameters (`...args`) instead of `arguments` in arrows. These omissions\nare why arrows are lightweight callbacks, not general-purpose functions.\n",{"id":2824,"difficulty":63,"q":2825,"a":2826},"this-prototype","What is this in a prototype method?","A method on a constructor's `prototype` behaves like any method: when called as\n`instance.method()`, `this` is the **instance**. The method lives once on the\nprototype but `this` resolves per call to whichever instance invoked it.\n\n```js\nfunction User(name) { this.name = name }\nUser.prototype.greet = function () { return `Hi, ${this.name}` }\nconst u = new User('Ada')\nu.greet() \u002F\u002F 'Hi, Ada' — this === u\n```\n\nThis is how one shared prototype method serves all instances correctly — `this`\nis determined by the call site, not where the method is defined.\n",{"description":61},"JavaScript `this` interview questions — how this is bound, arrow vs regular functions, call\u002Fapply\u002Fbind and common context bugs.","javascript\u002Ffunctions\u002Fthis-keyword","The this Keyword","T0rjf5OhY_1gyL0HET2e_qhZvmR8BBTBn2VHHhuvRuI",{"id":2833,"title":2834,"body":2835,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":2839,"navigation":66,"order":22,"path":2840,"questions":2841,"related":207,"seo":2972,"seoDescription":2973,"stem":2974,"subtopic":2975,"topic":667,"topicSlug":668,"updated":1525,"__hash__":2976},"qa\u002Fjavascript\u002Ffundamentals\u002Fdata-types-coercion.md","Data Types Coercion",{"type":58,"value":2836,"toc":2837},[],{"title":61,"searchDepth":22,"depth":22,"links":2838},[],{},"\u002Fjavascript\u002Ffundamentals\u002Fdata-types-coercion",[2842,2846,2850,2854,2858,2862,2865,2869,2873,2877,2881,2885,2889,2893,2897,2901,2905,2909,2913,2916,2920,2924,2928,2932,2936,2940,2944,2948,2952,2956,2960,2964,2968],{"id":2843,"difficulty":71,"q":2844,"a":2845},"primitives","What are the primitive types in JavaScript?","There are **seven primitive types**: `string`, `number`, `boolean`, `null`,\n`undefined`, `symbol`, and `bigint`. Everything that isn't a primitive is an\n**object** — and that includes arrays, functions, dates, and `null`'s\nmisleading `typeof`.\n\n```js\ntypeof 'hi'        \u002F\u002F 'string'\ntypeof 42          \u002F\u002F 'number'\ntypeof true        \u002F\u002F 'boolean'\ntypeof undefined   \u002F\u002F 'undefined'\ntypeof Symbol()    \u002F\u002F 'symbol'\ntypeof 10n         \u002F\u002F 'bigint'\ntypeof null        \u002F\u002F 'object'  \u003C- historical bug, null IS a primitive\n```\n\nTwo defining traits: primitives are **immutable** (you can't change the value\nitself, only rebind the variable) and they're **compared by value**, whereas\nobjects are mutable and **compared by reference**. When you call a method like\n`'hi'.toUpperCase()`, JS temporarily wraps the primitive in an object\n(autoboxing) and discards it afterward.\n",{"id":2847,"difficulty":71,"q":2848,"a":2849},"eqeq-vs-eqeqeq","What is the difference between == and ===?","`===` is **strict equality**: it compares **value *and* type** with no\nconversion — if the types differ, it's immediately `false`. `==` is **loose\nequality**: it **coerces** the operands toward a common type first, which\nproduces a list of surprising results.\n\n```js\n0 === ''      \u002F\u002F false (number vs string)\n0 == ''       \u002F\u002F true  (both coerce to 0)\n0 == '0'      \u002F\u002F true\n'' == '0'     \u002F\u002F false  \u003C- not even transitive!\nnull == undefined \u002F\u002F true (special-cased)\nNaN == NaN    \u002F\u002F false\n[] == ![]     \u002F\u002F true  (classic \"wtf\" — [] coerces to '', ![] is false -> 0)\n```\n\n**Prefer `===` virtually always** — it's predictable and the coercion rules\nbehind `==` are a frequent bug source. The one common idiomatic exception is\n`x == null`, which conveniently matches *both* `null` and `undefined`.\n",{"id":2851,"difficulty":63,"q":2852,"a":2853},"coercion","What is type coercion?","Coercion is JavaScript **automatically converting** a value from one type to\nanother. It comes in two flavors: **implicit** (the engine does it for you\nduring an operation, e.g. `'5' * 2`) and **explicit** (you ask for it,\n`Number('5')`, `String(5)`, `Boolean(0)`).\n\nThe operator that trips everyone up is `+`: if **either** side is a string, it\ndoes **string concatenation**; otherwise it does numeric addition. The other\narithmetic operators (`-`, `*`, `\u002F`) have no string meaning, so they coerce to\nnumbers.\n\n```js\n1 + '2'    \u002F\u002F '12'   (+ with a string -> concatenation)\n1 - '2'    \u002F\u002F -1     (- forces numeric -> 1 - 2)\n'5' * '2'  \u002F\u002F 10     (* forces numeric)\ntrue + 1   \u002F\u002F 2      (true -> 1)\n[] + {}    \u002F\u002F '[object Object]'  (both -> strings)\n```\n\nIn an interview, narrate the rule (\"`+` prefers strings, the rest prefer\nnumbers\") rather than memorizing every edge case.\n",{"id":2855,"difficulty":71,"q":2856,"a":2857},"truthy-falsy","Which values are falsy in JavaScript?","There are exactly **eight falsy values** — memorize the list, because\n*everything else is truthy*:\n\n```js\nfalse\n0\n-0\n0n        \u002F\u002F BigInt zero\n''        \u002F\u002F empty string\nnull\nundefined\nNaN\n```\n\nThe famous gotchas are the things people *expect* to be falsy but aren't:\n`'0'`, `'false'`, `[]` (empty array), and `{}` (empty object) are **all\ntruthy**.\n\n```js\nif ([]) console.log('runs!')   \u002F\u002F empty array is truthy\nif ('0') console.log('runs!')  \u002F\u002F non-empty string is truthy\nBoolean([]) \u002F\u002F true\n```\n\nThis matters for `if` conditions, `||`\u002F`&&`, and the nullish coalescing\noperator `??` (which, unlike `||`, only falls back on `null`\u002F`undefined`, not\non `0` or `''`).\n",{"id":2859,"difficulty":63,"q":2860,"a":2861},"null-undefined","What is the difference between null and undefined?","Both represent \"no value,\" but they signal different *intents*:\n\n- `undefined` is the language's default \"absence\" — a declared-but-unassigned\n  variable, a missing object property, a missing function argument, or the\n  return of a function with no `return`. The **engine** produces it.\n- `null` is an **intentional, explicit** \"no value here\" that **you** assign to\n  say \"this is deliberately empty.\"\n\n```js\nlet a               \u002F\u002F undefined (never assigned)\nconst obj = {}\nobj.missing         \u002F\u002F undefined (no such property)\nconst b = null      \u002F\u002F null (you chose emptiness)\n\ntypeof undefined    \u002F\u002F 'undefined'\ntypeof null         \u002F\u002F 'object'  \u003C- long-standing bug, never fixed for compat\nnull == undefined   \u002F\u002F true  (loose — they're \"equal absences\")\nnull === undefined  \u002F\u002F false (different types)\n```\n",{"id":2863,"difficulty":63,"q":949,"a":2864},"typeof-array","Use **`Array.isArray(value)`**. You can't use `typeof`, because arrays are\nobjects, so `typeof []` returns `'object'` — indistinguishable from a plain\nobject or `null`.\n\n```js\ntypeof []              \u002F\u002F 'object'  \u003C- useless for arrays\nArray.isArray([])      \u002F\u002F true\nArray.isArray({})      \u002F\u002F false\nArray.isArray('abc')   \u002F\u002F false\n```\n\n`Array.isArray` is also more robust than the older\n`value instanceof Array` trick, because `instanceof` **breaks across\nrealms** (e.g. an array coming from an `\u003Ciframe>` has a different `Array`\nconstructor, so `instanceof` returns `false`). `Array.isArray` works\nregardless of realm.\n",{"id":2866,"difficulty":84,"q":2867,"a":2868},"nan","Why is NaN === NaN false, and how do you test for NaN?","`NaN` (\"Not-a-Number\") is, by the IEEE-754 spec and ECMAScript, the **only\nvalue not equal to itself** — there are many distinct computations that produce\n\"not a number,\" so the standard defines all comparisons with `NaN` (including\n`NaN === NaN`) as `false`. You therefore can't detect it with `===`.\n\n```js\nNaN === NaN          \u002F\u002F false\n0 \u002F 0                \u002F\u002F NaN\nNumber('abc')        \u002F\u002F NaN\n\nNumber.isNaN(NaN)    \u002F\u002F true  reliable\nNumber.isNaN('abc')  \u002F\u002F false (no coercion — 'abc' simply isn't NaN)\n\nisNaN('abc')         \u002F\u002F true  misleading: it coerces 'abc' -> NaN first\n```\n\nUse **`Number.isNaN(value)`** (ES2015), which checks \"is this *literally* the\nNaN value.\" Avoid the **global `isNaN`**, which coerces its argument to a number\nfirst and so reports `true` for plenty of non-NaN inputs. (Another trick that\nworks: `value !== value` is `true` only for `NaN`.)\n",{"id":2870,"difficulty":63,"q":2871,"a":2872},"object-is","What is Object.is and how does it differ from ===?","`Object.is(a, b)` is \"same-value\" equality. It behaves like `===` **except** for\ntwo edge cases: it treats `NaN` as equal to itself, and it distinguishes `+0`\nfrom `-0`.\n\n```js\nObject.is(NaN, NaN)  \u002F\u002F true   (=== gives false)\nObject.is(0, -0)     \u002F\u002F false  (=== gives true)\nObject.is(1, 1)      \u002F\u002F true\n```\n\nIt's the same algorithm React uses to decide whether state\u002Fprops changed. Use\n`===` for normal comparisons; reach for `Object.is` when those two `NaN`\u002F`-0`\nedge cases actually matter.\n",{"id":2874,"difficulty":84,"q":2875,"a":2876},"plus-minus-zero","What is the difference between +0 and -0?","JavaScript has a signed zero: `+0` and `-0` are distinct bit patterns. They're\n**equal** under `==` and `===`, but distinguishable with `Object.is` or by\ndividing (which exposes the sign via `Infinity`).\n\n```js\n+0 === -0           \u002F\u002F true\nObject.is(+0, -0)   \u002F\u002F false\n1 \u002F +0              \u002F\u002F Infinity\n1 \u002F -0              \u002F\u002F -Infinity\n```\n\n`-0` arises from operations like `-1 * 0` or `Math.round(-0.1)`. It rarely matters,\nbut can surprise you in sign-sensitive math or when used as a Map key.\n",{"id":2878,"difficulty":71,"q":2879,"a":2880},"typeof-function","What does typeof return for a function?","`typeof` returns `'function'` for any callable — function declarations,\nexpressions, arrows, classes, and methods. This is a special case: functions are\ntechnically objects, but `typeof` singles them out.\n\n```js\ntypeof function () {}  \u002F\u002F 'function'\ntypeof (() => {})      \u002F\u002F 'function'\ntypeof class {}        \u002F\u002F 'function' (classes are functions under the hood)\ntypeof Math.max        \u002F\u002F 'function'\ntypeof []              \u002F\u002F 'object' (arrays are NOT singled out)\n```\n\nIt's the reliable way to check \"is this callable?\" before invoking\n(`typeof cb === 'function'`).\n",{"id":2882,"difficulty":63,"q":2883,"a":2884},"typeof-results","What are all the possible results of typeof?","`typeof` returns one of eight strings:\n\n```js\ntypeof 'a'        \u002F\u002F 'string'\ntypeof 1          \u002F\u002F 'number'\ntypeof true       \u002F\u002F 'boolean'\ntypeof undefined  \u002F\u002F 'undefined'\ntypeof 10n        \u002F\u002F 'bigint'\ntypeof Symbol()   \u002F\u002F 'symbol'\ntypeof function(){}\u002F\u002F 'function'\ntypeof {}         \u002F\u002F 'object'  (also arrays, null, dates, etc.)\n```\n\nThe famous quirk is **`typeof null === 'object'`** — a bug kept for backward\ncompatibility. Anything not in the first seven categories (including arrays and\n`null`) reports `'object'`, which is why you need `Array.isArray` and\n`=== null`.\n",{"id":2886,"difficulty":84,"q":2887,"a":2888},"boxing","What is autoboxing of primitives?","Primitives have no methods, yet `'hi'.toUpperCase()` works because JavaScript\ntemporarily **wraps** the primitive in its object form (`String`, `Number`,\n`Boolean`), calls the method, then discards the wrapper.\n\n```js\n'hi'.length        \u002F\u002F 2 — boxed to a String object momentarily\n(5).toFixed(2)     \u002F\u002F '5.00' — boxed to Number\n\n\u002F\u002F explicit wrapper objects are an anti-pattern:\nconst n = new Number(5)\ntypeof n           \u002F\u002F 'object', not 'number'\nn === 5            \u002F\u002F false\n```\n\nNever use `new Number`\u002F`new String` — the resulting objects break `===` and are\nalways truthy (`new Boolean(false)` is truthy!). Let autoboxing happen\nimplicitly.\n",{"id":2890,"difficulty":63,"q":2891,"a":2892},"parseint-vs-number","What is the difference between parseInt and Number?","- **`Number(x)`** converts the **entire** string to a number; any invalid\n  character makes the whole thing `NaN`. Handles decimals.\n- **`parseInt(x, radix)`** reads an **integer prefix**, stopping at the first\n  non-numeric character, and ignores the rest. Always pass the radix.\n\n```js\nNumber('42px')      \u002F\u002F NaN\nparseInt('42px', 10)\u002F\u002F 42 (parses the leading 42)\nNumber('3.14')      \u002F\u002F 3.14\nparseInt('3.14', 10)\u002F\u002F 3 (integer only)\nparseInt('0x1F', 16)\u002F\u002F 31\nNumber('')          \u002F\u002F 0  (parseInt('') is NaN)\n```\n\nUse `Number`\u002F`parseFloat` for exact full-string conversion; `parseInt` for\nextracting a leading integer (e.g. `'20px'` -> `20`).\n",{"id":2894,"difficulty":84,"q":2895,"a":2896},"eqeq-steps","What steps does == take to coerce operands?","The abstract equality (`==`) algorithm, simplified:\n\n1. Same type -> compare like `===`.\n2. `null == undefined` -> `true` (and they equal nothing else).\n3. number vs string -> convert the **string to a number**.\n4. boolean vs anything -> convert the **boolean to a number** (`true`->1, `false`->0).\n5. object vs primitive -> convert the **object to a primitive** (`valueOf`\u002F\n   `toString`), then retry.\n\n```js\n'5' == 5      \u002F\u002F string->number: 5 == 5 -> true\ntrue == 1     \u002F\u002F boolean->number: 1 == 1 -> true\n[] == 0       \u002F\u002F [] -> '' -> 0; 0 == 0 -> true\n[] == ![]     \u002F\u002F ![] is false->0; [] -> 0; true\n```\n\nKnowing these steps explains every \"wat\" example — and is the best argument for\nalways using `===`.\n",{"id":2898,"difficulty":84,"q":2899,"a":2900},"toprimitive","How does an object convert to a primitive (Symbol.toPrimitive)?","When an object is used where a primitive is expected, JS calls its\n`Symbol.toPrimitive` method (if present) with a **hint** (`'number'`, `'string'`,\nor `'default'`); otherwise it falls back to `valueOf` then `toString`.\n\n```js\nconst money = {\n  amount: 100,\n  [Symbol.toPrimitive](hint) {\n    return hint === 'string' ? `$${this.amount}` : this.amount\n  },\n}\n`${money}`   \u002F\u002F '$100'  (hint 'string')\nmoney + 1    \u002F\u002F 101     (hint 'default' -> number)\nmoney * 2    \u002F\u002F 200     (hint 'number')\n```\n\nThis lets you control how objects behave in concatenation, arithmetic, and\ntemplate literals.\n",{"id":2902,"difficulty":63,"q":2903,"a":2904},"valueof-tostring","What roles do valueOf and toString play in coercion?","Without `Symbol.toPrimitive`, object-to-primitive conversion uses these two: for a\n**number** hint it tries `valueOf` first; for a **string** hint it tries\n`toString` first. Whichever returns a primitive wins.\n\n```js\nconst obj = {\n  valueOf() { return 42 },\n  toString() { return 'hello' },\n}\nobj + 1       \u002F\u002F 43      (default\u002Fnumber hint -> valueOf)\n`${obj}`      \u002F\u002F 'hello' (string hint -> toString)\nString(obj)   \u002F\u002F 'hello'\nNumber(obj)   \u002F\u002F 42\n```\n\nOverride `toString` (and sometimes `valueOf`) to make your objects coerce\nsensibly in logs and expressions.\n",{"id":2906,"difficulty":71,"q":2907,"a":2908},"template-coercion","How does coercion work in template literals?","Template literals coerce every interpolated value to a **string** (using\n`String()` \u002F the object's `toString`). This is convenient but can produce\n`[object Object]` or `undefined`\u002F`null` text.\n\n```js\n`count: ${5}`        \u002F\u002F 'count: 5'\n`arr: ${[1, 2, 3]}`  \u002F\u002F 'arr: 1,2,3' (array toString joins with commas)\n`obj: ${ {a: 1} }`   \u002F\u002F 'obj: [object Object]'\n`val: ${null}`       \u002F\u002F 'val: null'\n```\n\nFor objects, interpolate a specific field or `JSON.stringify(obj)` rather than\nrelying on the default `[object Object]`.\n",{"id":2910,"difficulty":84,"q":2911,"a":2912},"json-stringify","What are the edge cases of JSON.stringify?","`JSON.stringify` silently **drops or transforms** several types: `undefined`,\nfunctions, and symbols are **omitted** in objects (or become `null` in arrays);\n`NaN`\u002F`Infinity` become `null`; `BigInt` **throws**; and `Date` becomes an ISO\nstring.\n\n```js\nJSON.stringify({ a: undefined, b: () => {}, c: NaN })\n\u002F\u002F '{\"c\":null}'  — a and b dropped, NaN -> null\nJSON.stringify([undefined, function(){}, 1])\n\u002F\u002F '[null,null,1]'\nJSON.stringify(10n) \u002F\u002F TypeError: BigInt not serializable\n```\n\nIt also calls a value's `toJSON()` if present, and ignores non-enumerable\nproperties. Know these when serializing for APIs or storage.\n",{"id":576,"difficulty":63,"q":2914,"a":2915},"Why does 0.1 + 0.2 not equal 0.3 in JavaScript?","All JS numbers are 64-bit IEEE-754 **doubles**. Decimal fractions like `0.1` can't\nbe represented exactly in binary, so they're stored as the nearest approximation\nand rounding errors accumulate.\n\n```js\n0.1 + 0.2            \u002F\u002F 0.30000000000000004\n0.1 + 0.2 === 0.3    \u002F\u002F false\n\n\u002F\u002F compare with a tolerance instead:\nMath.abs(0.1 + 0.2 - 0.3) \u003C Number.EPSILON \u002F\u002F true\n```\n\nFor money, work in integer **cents** or use a decimal library. Never compare\nfloats with `===`; use an epsilon tolerance.\n",{"id":2917,"difficulty":63,"q":2918,"a":2919},"bigint","What is BigInt and how does it differ from Number?","`BigInt` represents integers of **arbitrary precision**, beyond the safe integer\nlimit of `Number` (`2^53 - 1`). Create one with an `n` suffix or `BigInt()`.\n\n```js\nNumber.MAX_SAFE_INTEGER          \u002F\u002F 9007199254740991\n9007199254740991 + 2             \u002F\u002F 9007199254740992 (wrong! lost precision)\n9007199254740991n + 2n           \u002F\u002F 9007199254740993n (exact)\n```\n\nCaveats: you **can't mix** `BigInt` and `Number` in arithmetic (`1n + 1` throws),\n`typeof 1n === 'bigint'`, and it's integer-only (no decimals). Use it for large\nIDs, timestamps in nanoseconds, and exact big-integer math.\n",{"id":2921,"difficulty":63,"q":2922,"a":2923},"nullish-coalescing","What is the nullish coalescing operator (??)?","`a ?? b` returns `b` **only when `a` is `null` or `undefined`** — unlike `||`,\nwhich falls back on **any** falsy value (`0`, `''`, `false`). This makes `??`\ncorrect for defaults where `0`\u002F`''` are valid.\n\n```js\nconst count = 0\ncount || 10   \u002F\u002F 10  treats valid 0 as \"missing\"\ncount ?? 10   \u002F\u002F 0   only null\u002Fundefined trigger the default\n\nconst name = '' ?? 'anon' \u002F\u002F '' (empty string is kept)\n```\n\nUse `??` when only \"absent\" should trigger the fallback. You can't mix `??`\ndirectly with `&&`\u002F`||` without parentheses (a syntax error by design).\n",{"id":2925,"difficulty":71,"q":2926,"a":2927},"optional-chaining","What is optional chaining (?.)?","`?.` short-circuits to `undefined` if the value before it is `null`\u002F`undefined`,\ninstead of throwing — letting you safely access deep properties, call maybe-\nmissing methods, and index possibly-absent values.\n\n```js\nuser?.address?.city        \u002F\u002F undefined if user or address is null\nuser?.getName?.()          \u002F\u002F calls only if getName exists\narr?.[0]                   \u002F\u002F safe index access\n```\n\nIt pairs naturally with `??`: `user?.name ?? 'anon'`. Note it stops at the first\nnullish link and only guards against `null`\u002F`undefined` — not other errors.\n",{"id":2929,"difficulty":63,"q":2930,"a":2931},"array-equality","How do you compare two arrays or objects for equality?","`===` compares **references**, so two distinct arrays\u002Fobjects with identical\ncontents are **not** equal. You must compare contents yourself.\n\n```js\n[1, 2] === [1, 2]   \u002F\u002F false (different references)\n\n\u002F\u002F shallow array compare:\nconst eq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i])\n\u002F\u002F quick (but flawed) deep compare:\nJSON.stringify(a) === JSON.stringify(b) \u002F\u002F order\u002Fundefined-sensitive\n```\n\n`JSON.stringify` works for simple data but breaks on key order, `undefined`,\nfunctions, and cycles. For robust deep equality, use a library (lodash\n`isEqual`).\n",{"id":2933,"difficulty":71,"q":2934,"a":2935},"string-number-conversion","What are the ways to convert a string to a number?","Several, with different strictness:\n\n```js\nNumber('42')     \u002F\u002F 42      (whole string; '' -> 0, '4a' -> NaN)\nparseInt('42px', 10) \u002F\u002F 42  (leading integer)\nparseFloat('3.14m') \u002F\u002F 3.14 (leading float)\n+'42'            \u002F\u002F 42      (unary plus — concise coercion)\n'42' * 1         \u002F\u002F 42      (arithmetic coercion)\n```\n\n`Number()`\u002Funary `+` are strict (invalid -> `NaN`); `parseInt`\u002F`parseFloat` are\nlenient (parse a prefix). Always validate with `Number.isNaN` afterward when the\ninput is untrusted.\n",{"id":2937,"difficulty":71,"q":2938,"a":2939},"boolean-double-bang","What does the double-bang (!!) operator do?","`!!x` coerces any value to its **boolean** equivalent. The first `!` converts to\nthe inverted boolean, the second `!` flips it back — giving the truthiness as a\nreal `true`\u002F`false`.\n\n```js\n!!'hello'   \u002F\u002F true\n!!0         \u002F\u002F false\n!!null      \u002F\u002F false\n!![]        \u002F\u002F true  (empty array is truthy)\nBoolean('hello') \u002F\u002F true — equivalent, more explicit\n```\n\nIt's a common idiom to normalize a value to a strict boolean (e.g. before\nreturning from a predicate or storing a flag). `Boolean(x)` does the same thing\nmore readably.\n",{"id":2941,"difficulty":63,"q":2942,"a":2943},"symbol","What is a Symbol and what is it used for?","A `Symbol` is a **unique, immutable** primitive, mainly used as **non-colliding\nobject keys**. Every `Symbol()` is distinct, even with the same description.\n\n```js\nconst id = Symbol('id')\nconst obj = { [id]: 123 }\nobj[id]              \u002F\u002F 123\nSymbol('x') === Symbol('x') \u002F\u002F false — always unique\n```\n\nUses: private-ish keys (not enumerable in `for...in`\u002F`JSON.stringify`), and\n**well-known symbols** that customize behavior (`Symbol.iterator`,\n`Symbol.toPrimitive`, `Symbol.asyncIterator`). `Symbol.for('k')` accesses a\nshared global registry.\n",{"id":2945,"difficulty":84,"q":2946,"a":2947},"array-coercion","How do arrays coerce to primitives?","An array's `toString` joins its elements with commas. So an empty array becomes\n`''`, a single-element array becomes that element's string, and `+` with a string\nconcatenates — leading to several classic surprises.\n\n```js\n[] + []        \u002F\u002F ''        (both -> '')\n[] + {}        \u002F\u002F '[object Object]'\n[1, 2] + [3]   \u002F\u002F '1,23'    ('1,2' + '3')\nNumber([])     \u002F\u002F 0         ('' -> 0)\nNumber([5])    \u002F\u002F 5         ('5' -> 5)\nNumber([1, 2]) \u002F\u002F NaN       ('1,2' -> NaN)\n```\n\nThese underpin the `[] == ![]` brain-teasers. The rule: array -> string (comma\njoin) -> then number if needed.\n",{"id":2949,"difficulty":63,"q":2950,"a":2951},"nan-operations","Which operations produce NaN?","`NaN` results from **invalid or undefined mathematical operations** — converting\nnon-numeric strings, `0\u002F0`, `Infinity - Infinity`, or arithmetic on `undefined`.\nAnd `NaN` is **contagious**: any arithmetic with it yields `NaN`.\n\n```js\nNumber('abc')          \u002F\u002F NaN\n0 \u002F 0                  \u002F\u002F NaN\nMath.sqrt(-1)          \u002F\u002F NaN\nundefined + 1          \u002F\u002F NaN\nparseInt('xyz', 10)    \u002F\u002F NaN\nNaN + 5                \u002F\u002F NaN (propagates)\n```\n\nBecause it spreads, a single bad value can turn a whole calculation into `NaN` —\nguard inputs and check with `Number.isNaN`.\n",{"id":2953,"difficulty":63,"q":2954,"a":2955},"undefined-not-defined","What is the difference between undefined and \"not defined\"?","**`undefined`** is a value: a declared variable that hasn't been assigned, or a\nmissing property. **\"Not defined\"** means the identifier doesn't exist at all —\naccessing it throws a **`ReferenceError`**.\n\n```js\nlet a\nconsole.log(a)         \u002F\u002F undefined (declared, no value)\nconsole.log(b)         \u002F\u002F ReferenceError: b is not defined\n\nconst obj = {}\nconsole.log(obj.x)     \u002F\u002F undefined (missing property, no error)\n```\n\nSo `undefined` is recoverable (it's just a value); a \"not defined\" reference is an\nerror. `typeof` is the safe way to check the latter without throwing.\n",{"id":2957,"difficulty":63,"q":2958,"a":2959},"typeof-undeclared","Why doesn't typeof throw on an undeclared variable?","`typeof` is special-cased to **not throw** a `ReferenceError` for an undeclared\nidentifier — it returns `'undefined'`. This makes it the safe way to feature-\ndetect a global that may not exist.\n\n```js\ntypeof someUndeclaredVar  \u002F\u002F 'undefined' (no error)\nsomeUndeclaredVar         \u002F\u002F ReferenceError\n\n\u002F\u002F safe environment checks:\nif (typeof window !== 'undefined') { \u002F* browser *\u002F }\n```\n\nCaveat: this leniency does **not** apply to `let`\u002F`const` in the temporal dead\nzone — `typeof x` before a `let x` declaration still throws.\n",{"id":2961,"difficulty":63,"q":2962,"a":2963},"immutable-primitives","What does it mean that primitives are immutable?","A primitive value itself can never be changed — operations that look like\nmutation actually create a **new** value. You can reassign the variable, but the\noriginal primitive is untouched.\n\n```js\nlet s = 'hello'\ns.toUpperCase()  \u002F\u002F 'HELLO' (a new string)\nconsole.log(s)   \u002F\u002F 'hello' (original unchanged)\ns[0] = 'J'       \u002F\u002F silently fails (or throws in strict mode)\ns = 'world'      \u002F\u002F reassigning the variable is fine\n```\n\nContrast objects\u002Farrays, which are mutable (you can change their contents in\nplace). Immutability is why primitives compare by value and are safe to share.\n",{"id":2965,"difficulty":63,"q":2966,"a":2967},"string-comparison","How does JavaScript compare strings with \u003C and >?","Relational operators compare strings **lexicographically** by UTF-16 code unit,\ncharacter by character. This is case-sensitive (uppercase letters have lower code\npoints than lowercase) and not locale-aware.\n\n```js\n'apple' \u003C 'banana'  \u002F\u002F true\n'Z' \u003C 'a'           \u002F\u002F true  (90 \u003C 97)\n'10' \u003C '9'          \u002F\u002F true  (string compare: '1' \u003C '9')\n'10' \u003C 9            \u002F\u002F false (mixed -> numeric: 10 \u003C 9)\n```\n\nFor human-friendly, locale-aware ordering (accents, case-insensitive), use\n`a.localeCompare(b)`. Note mixed string\u002Fnumber comparisons coerce to numbers.\n",{"id":2969,"difficulty":84,"q":2970,"a":2971},"deep-vs-shallow-equality","What is the difference between shallow and deep equality?","**Shallow** equality compares the top level: same reference, or matching primitive\nvalues \u002F first-level properties. **Deep** equality recursively compares nested\nstructures for equivalent contents.\n\n```js\nconst a = { x: { y: 1 } }\nconst b = { x: { y: 1 } }\na.x === b.x          \u002F\u002F false (different nested references)\n\u002F\u002F shallow: equal keys but nested refs differ -> not equal\n\u002F\u002F deep: recursively equal -> equal\n```\n\nReact uses shallow comparison for re-render decisions (props\u002Fstate), which is why\nmutating nested objects can be missed. Deep equality (lodash `isEqual`) is\ncostlier but compares full structure.\n",{"description":61},"JavaScript interview questions on primitive types, type coercion, == vs ===, truthy\u002Ffalsy values and checking types, with examples.","javascript\u002Ffundamentals\u002Fdata-types-coercion","Data Types & Coercion","vp9_844foLQtkq0K684OgyEhpivBJuIJMeUrLOlNC0k",{"id":2978,"title":2979,"body":2980,"description":61,"difficulty":71,"extension":64,"framework":11,"frameworkSlug":9,"meta":2984,"navigation":66,"order":12,"path":2985,"questions":2986,"related":207,"seo":3119,"seoDescription":3120,"stem":3121,"subtopic":3122,"topic":667,"topicSlug":668,"updated":1525,"__hash__":3123},"qa\u002Fjavascript\u002Ffundamentals\u002Fvariables-scope-hoisting.md","Variables Scope Hoisting",{"type":58,"value":2981,"toc":2982},[],{"title":61,"searchDepth":22,"depth":22,"links":2983},[],{},"\u002Fjavascript\u002Ffundamentals\u002Fvariables-scope-hoisting",[2987,2991,2995,2999,3003,3007,3011,3015,3019,3023,3027,3031,3035,3039,3043,3047,3051,3055,3059,3063,3067,3071,3075,3079,3083,3087,3091,3095,3099,3103,3107,3111,3115],{"id":2988,"difficulty":71,"q":2989,"a":2990},"var-let-const","What is the difference between var, let and const?","They differ along three axes: **scope**, **hoisting\u002Finitialization**, and\n**reassignment**.\n\n| Keyword | Scope    | Hoisted? | Reassignable? | Redeclarable? |\n| ------- | -------- | -------- | ------------- | ------------- |\n| `var`   | function | yes, init `undefined` | yes | yes |\n| `let`   | block    | yes, in TDZ (uninit)  | yes | no  |\n| `const` | block    | yes, in TDZ (uninit)  | no  | no  |\n\nThe subtle one is `const`: it makes the **binding** constant, **not the\nvalue**. You can't reassign the variable, but if it holds an object or array\nyou can still mutate the contents.\n\n```js\nconst user = { name: 'Ada' }\nuser.name = 'Grace' \u002F\u002F OK — mutating the object the binding points to\nuser = {}           \u002F\u002F TypeError — reassigning the binding\n\nconst list = [1, 2]\nlist.push(3)        \u002F\u002F [1, 2, 3]\n```\n\nModern guidance: default to `const`, use `let` when you genuinely need to\nreassign, and avoid `var`.\n",{"id":2992,"difficulty":63,"q":2993,"a":2994},"hoisting","What is hoisting?","Hoisting is the JavaScript engine processing **declarations** before executing\ncode, so they behave as if \"moved\" to the top of their scope. But *what* gets\nhoisted differs:\n\n- `var` declarations are hoisted **and initialized to `undefined`**, so reading\n  one before its assignment gives `undefined` (no error).\n- **Function declarations** are hoisted **entirely** — you can call them above\n  where they're written.\n- `let`\u002F`const` are hoisted **but left uninitialized** in the *temporal dead\n  zone*; touching them early throws.\n\n```js\nconsole.log(a) \u002F\u002F undefined  (var hoisted, value not yet assigned)\nvar a = 1\n\ngreet()        \u002F\u002F 'hi'  (function declaration fully hoisted)\nfunction greet() { return 'hi' }\n\nconsole.log(b) \u002F\u002F ReferenceError (TDZ)\nlet b = 2\n```\n\nMental model: declarations are \"registered\" first; only the **assignments**\nrun in place.\n",{"id":2996,"difficulty":63,"q":2997,"a":2998},"tdz","What is the temporal dead zone (TDZ)?","The TDZ is the window between **entering a scope** and the line where a\n`let`\u002F`const` variable is actually **declared**. The binding exists (it was\nhoisted) but is *uninitialized*, so any attempt to read or write it in that\nwindow throws a `ReferenceError`.\n\n```js\n{\n  \u002F\u002F TDZ for `x` starts here\n  console.log(x) \u002F\u002F ReferenceError: Cannot access 'x' before initialization\n  let x = 5      \u002F\u002F TDZ ends — x is now initialized\n  console.log(x) \u002F\u002F 5\n}\n```\n\nIt exists on purpose: it turns \"used before declared\" from a silent\n`undefined` bug (the `var` behavior) into a **loud, immediate error**, which\ncatches mistakes earlier and makes `const` semantics sound.\n",{"id":3000,"difficulty":71,"q":3001,"a":3002},"block-scope","What is the difference between block scope and function scope?","**Function scope** (`var`) means a variable is visible **anywhere inside the\nenclosing function**, regardless of which `{ }` blocks it's nested in. **Block\nscope** (`let`\u002F`const`) confines a variable to the **nearest pair of braces** —\nincluding `if`, `for`, `while`, and even a bare `{ }` block.\n\n```js\nfunction demo() {\n  if (true) {\n    var v = 'function-scoped'\n    let l = 'block-scoped'\n  }\n  console.log(v) \u002F\u002F 'function-scoped' — var leaks out of the if\n  console.log(l) \u002F\u002F ReferenceError — l only exists inside the if\n}\n```\n\nBlock scoping is generally safer: variables stay where they're relevant and\nyou avoid accidental leakage across a function — which is one big reason `let`\u002F\n`const` replaced `var`.\n",{"id":3004,"difficulty":71,"q":3005,"a":3006},"redeclare","Can you redeclare variables in the same scope?","`var` lets you **redeclare** the same name in the same scope without\ncomplaint — which silently masks bugs and accidental overwrites. `let` and\n`const` **throw a `SyntaxError`** if you redeclare an identifier in the same\nscope.\n\n```js\nvar x = 1\nvar x = 2      \u002F\u002F allowed (and easy to do by accident)\n\nlet y = 1\nlet y = 2      \u002F\u002F SyntaxError: Identifier 'y' has already been declared\n```\n\nNote this is about *redeclaration in the same scope*. You can still\n**shadow** a `let` in a nested inner block with a new `let` of the same name —\nthat creates a separate binding and is perfectly legal.\n",{"id":3008,"difficulty":63,"q":3009,"a":3010},"global-this","Do var, let and const create properties on the global object?","At the **top level** of a script, a `var` declaration *also* creates a property\non the global object (`window` in browsers, `globalThis` generally). `let` and\n`const` do **not** — they create bindings in a separate *script-scoped* record\nthat the global object can't see.\n\n```js\nvar a = 1\nlet b = 2\nconst c = 3\n\nwindow.a \u002F\u002F 1          \u003C- var leaked onto the global object\nwindow.b \u002F\u002F undefined  \u003C- let did not\nwindow.c \u002F\u002F undefined\n```\n\nThis is another reason to avoid top-level `var`: it pollutes the global\nnamespace and can clash with other scripts or built-ins. (Inside ES modules,\neven top-level `var` doesn't attach to the global object, since module scope\nisn't global scope.)\n",{"id":3012,"difficulty":84,"q":3013,"a":3014},"loop-closure","Why does var behave unexpectedly in a for loop with closures?","Because `var` is **function-scoped**, the loop reuses **one single binding**\nacross all iterations. Any callbacks created in the loop close over that *same*\nvariable, so when they run later they all read its **final value**. `let`\ncreates a **fresh binding each iteration**, so each closure captures its own\ncopy.\n\n```js\nfor (var i = 0; i \u003C 3; i++) setTimeout(() => console.log(i)) \u002F\u002F 3 3 3\nfor (let j = 0; j \u003C 3; j++) setTimeout(() => console.log(j)) \u002F\u002F 0 1 2\n```\n\nWith `var`, by the time the timers fire the loop has long finished and `i` is\n`3`. With `let`, the language re-binds `j` per iteration (and even copies the\nvalue forward for the increment), giving each callback `0`, `1`, `2`. The\npre-`let` fix was an IIFE to manufacture a new scope each pass.\n",{"id":3016,"difficulty":71,"q":3017,"a":3018},"const-array","Can you modify an array declared with const?","Yes. `const` freezes the **binding**, not the **value**. The variable must keep\npointing at the same array, but the array's contents are fully mutable.\n\n```js\nconst arr = [1, 2, 3]\narr.push(4)      \u002F\u002F [1, 2, 3, 4]\narr[0] = 99      \u002F\u002F [99, 2, 3, 4]\narr.length = 0   \u002F\u002F [] — still the same array\narr = []         \u002F\u002F TypeError: Assignment to constant variable\n```\n\nIf you want the *contents* to be immutable too, that's a separate concern —\nuse `Object.freeze(arr)` for a shallow freeze (and note `freeze` is shallow, so\nnested objects can still change).\n",{"id":3020,"difficulty":63,"q":3021,"a":3022},"lexical-scope","What is lexical scope?","Lexical (static) scope means a variable's accessibility is determined by **where\nit's written** in the source code — the nesting of functions\u002Fblocks — not by where\nor how a function is called. The structure is fixed at author time.\n\n```js\nconst outer = 1\nfunction f() {\n  const inner = 2\n  function g() { return outer + inner } \u002F\u002F sees both by lexical nesting\n  return g()\n}\nf() \u002F\u002F 3\n```\n\nBecause scope is determined by position, you can tell what any function can access\njust by reading the code. JavaScript uses lexical scope (unlike languages with\ndynamic scope).\n",{"id":3024,"difficulty":63,"q":3025,"a":3026},"scope-chain","What is the scope chain?","When you reference a variable, the engine looks in the **current scope**, then its\n**enclosing scope**, and so on outward until the global scope — this series of\nlinked scopes is the scope chain. The first match wins; if none is found, it's a\n`ReferenceError`.\n\n```js\nconst a = 'global'\nfunction outer() {\n  const b = 'outer'\n  function inner() {\n    const c = 'inner'\n    return `${a} ${b} ${c}` \u002F\u002F resolves c->inner, b->outer, a->global\n  }\n  return inner()\n}\n```\n\nLookups go **inward-to-outward only** — an outer scope can't see inner variables.\nThis chain is also what closures preserve.\n",{"id":3028,"difficulty":63,"q":3029,"a":3030},"shadowing","What is variable shadowing?","Shadowing is declaring a variable in an inner scope with the **same name** as one\nin an outer scope. The inner variable \"shadows\" the outer one within that scope;\nthe outer remains unchanged outside.\n\n```js\nconst x = 1\nfunction f() {\n  const x = 2   \u002F\u002F shadows the outer x\n  console.log(x) \u002F\u002F 2\n}\nf()\nconsole.log(x)  \u002F\u002F 1 (outer untouched)\n```\n\nShadowing is legal and sometimes useful, but accidental shadowing causes bugs.\nNote you **can't** shadow with `var`\u002F`let` in a way that accesses the outer value\nmid-declaration (TDZ), and linters can warn on shadowing.\n",{"id":3032,"difficulty":84,"q":3033,"a":3034},"fn-decl-vs-block","How are function declarations scoped inside blocks?","In **strict mode** (the default in modules\u002Fclasses), a function declaration inside\na block is **block-scoped** — visible only within that block. In sloppy mode the\nbehavior is inconsistent across engines, which is a common gotcha.\n\n```js\n'use strict'\nif (true) {\n  function foo() { return 1 }\n}\ntypeof foo \u002F\u002F 'undefined' in strict mode — block-scoped\n```\n\nBest practice: don't declare functions inside blocks. Use a **function\nexpression** assigned to a `let`\u002F`const` if you need a conditionally-defined\nfunction, for predictable scoping.\n",{"id":3036,"difficulty":84,"q":3037,"a":3038},"let-switch","Why can let and const be tricky in a switch statement?","A `switch` has **one shared block scope** across all its `case`s. Declaring\n`let`\u002F`const` in one case puts it in the TDZ for the entire switch, so another case\ncan hit a `ReferenceError` or a redeclaration `SyntaxError`.\n\n```js\nswitch (x) {\n  case 1:\n    let y = 'a'   \u002F\u002F y is scoped to the whole switch\n    break\n  case 2:\n    let y = 'b'   \u002F\u002F SyntaxError: 'y' already declared\n    break\n}\n```\n\nFix by wrapping each case body in its own **block** `{ ... }`, giving each `case`\na separate scope.\n",{"id":3040,"difficulty":63,"q":3041,"a":3042},"fn-expr-hoist","Are function expressions hoisted?","The **variable** is hoisted, but the **function value is not** — only the\ndeclaration is. So calling a function expression before its assignment fails\n(`undefined`\u002FTDZ), unlike a function declaration which is fully hoisted.\n\n```js\ndeclared()  \u002F\u002F works — declaration hoisted\nfunction declared() {}\n\nexpressed() \u002F\u002F TypeError: expressed is not a function (var) \u002F ReferenceError (let)\nvar expressed = function () {}\n```\n\nSo function **declarations** are callable above their line; function\n**expressions** (including arrows) follow normal variable hoisting rules and\naren't.\n",{"id":3044,"difficulty":84,"q":3045,"a":3046},"class-hoist","Are class declarations hoisted?","Class declarations **are hoisted** but, like `let`\u002F`const`, remain in the\n**temporal dead zone** — so you **can't use a class before its declaration**.\nUnlike function declarations, they aren't callable early.\n\n```js\nnew Foo()  \u002F\u002F ReferenceError: Cannot access 'Foo' before initialization\nclass Foo {}\n\nbar()      \u002F\u002F function declarations work\nfunction bar() {}\n```\n\nSo \"classes are hoisted\" is technically true, but the TDZ means it behaves like\nnot-hoisted in practice. Always declare classes before using them.\n",{"id":3048,"difficulty":84,"q":3049,"a":3050},"named-fn-expr","What is a named function expression and why use one?","A named function expression gives the function a name that's **only visible inside\nits own body** (not the outer scope). It's useful for self-reference (recursion)\nand clearer stack traces.\n\n```js\nconst factorial = function fact(n) {\n  return n \u003C= 1 ? 1 : n * fact(n - 1) \u002F\u002F `fact` usable inside\n}\nfactorial(5) \u002F\u002F 120\nfact          \u002F\u002F ReferenceError — not visible outside\n```\n\nThe inner name is safer than relying on the outer variable (which could be\nreassigned) and shows up in debuggers instead of \"anonymous.\"\n",{"id":3052,"difficulty":71,"q":3053,"a":3054},"nested-scope-lookup","How does variable lookup work in nested functions?","An inner function can read variables from all of its enclosing scopes, resolved\nvia the scope chain. Each function adds a scope; lookups proceed outward until a\nmatch or the global scope.\n\n```js\nfunction a() {\n  let x = 1\n  function b() {\n    let y = 2\n    function c() { return x + y } \u002F\u002F reaches up two levels\n    return c()\n  }\n  return b()\n}\na() \u002F\u002F 3\n```\n\nInner scopes see outer variables, never the reverse. This nested visibility is the\nfoundation of closures.\n",{"id":3056,"difficulty":84,"q":3057,"a":3058},"implicit-global","What is an accidental (implicit) global variable?","Assigning to a variable **without declaring** it (`x = 5`) in sloppy mode creates\na property on the **global object** instead of erroring — a common source of bugs\nand leaks. **Strict mode** throws a `ReferenceError` instead.\n\n```js\nfunction f() {\n  count = 1   \u002F\u002F no var\u002Flet\u002Fconst -> implicit global\n}\nf()\nconsole.log(count) \u002F\u002F 1 (leaked to global!)\n\n\u002F\u002F strict mode:\n'use strict'\nfunction g() { total = 1 } \u002F\u002F ReferenceError\n```\n\nAlways declare variables, and use strict mode (automatic in modules) so this\nmistake fails loudly.\n",{"id":3060,"difficulty":63,"q":3061,"a":3062},"strict-mode-vars","How does strict mode change variable behavior?","Strict mode tightens several variable rules: assigning to an undeclared variable\n**throws** (no accidental globals), you can't `delete` a variable, duplicate\nparameter names are errors, and `this` is `undefined` instead of the global object\nin plain calls.\n\n```js\n'use strict'\nundeclared = 5   \u002F\u002F ReferenceError\nfunction dup(a, a) {} \u002F\u002F SyntaxError\n```\n\nES modules and class bodies are **always** strict. Strict mode surfaces bugs at\nauthor\u002Fparse time that would otherwise fail silently — a big reason modern code is\nstrict by default.\n",{"id":3064,"difficulty":71,"q":3065,"a":3066},"const-init","Why must a const be initialized at declaration?","Because `const` can be assigned **only once**, you must give it that value at\ndeclaration — there's no later opportunity to assign. Declaring without a value is\na `SyntaxError`.\n\n```js\nconst x = 5   \u002F\u002F\nconst y        \u002F\u002F SyntaxError: Missing initializer in const declaration\n```\n\n`let` and `var` can be declared without a value (defaulting to `undefined`), but\n`const`'s \"assign once\" contract requires the value up front. This also makes\n`const` ineligible for the classic split declare-then-assign pattern.\n",{"id":3068,"difficulty":84,"q":3069,"a":3070},"var-fn-clash","What happens when a var and a function declaration share a name?","During hoisting, **function declarations take precedence** over `var`\ndeclarations with the same name. The `var` declaration is ignored (its\nassignment, if any, still runs in place and can overwrite the function later).\n\n```js\nconsole.log(typeof foo) \u002F\u002F 'function' — function decl wins at hoist time\nvar foo = 'bar'\nfunction foo() {}\nconsole.log(typeof foo) \u002F\u002F 'string' — the assignment ran\n```\n\nSo at the top the name is the function; once execution reaches `foo = 'bar'`, it\nbecomes the string. These clashes are confusing — avoid reusing names.\n",{"id":3072,"difficulty":63,"q":3073,"a":3074},"module-scope","What is module scope?","Each ES module has its own **top-level scope** — variables declared at the top of\na module are **not** global; they're private to that module unless `export`ed.\nEven top-level `var` doesn't attach to the global object.\n\n```js\n\u002F\u002F module.js\nconst secret = 42       \u002F\u002F module-scoped, not global\nexport const api = {}   \u002F\u002F shared only via export\n\u002F\u002F window.secret -> undefined\n```\n\nThis is a major improvement over classic scripts, where top-level `var` polluted\nthe global namespace. Module scope plus strict mode is why modern code avoids many\nlegacy footguns.\n",{"id":3076,"difficulty":84,"q":3077,"a":3078},"let-per-iteration","How does let create a new binding each loop iteration?","In a `for` loop, `let` creates a **fresh binding per iteration** and copies the\nvalue forward — so closures created in the loop each capture their own copy. `var`\nshares one binding across all iterations.\n\n```js\nconst fns = []\nfor (let i = 0; i \u003C 3; i++) fns.push(() => i)\nfns.map(f => f())  \u002F\u002F [0, 1, 2]\n\nconst v = []\nfor (var j = 0; j \u003C 3; j++) v.push(() => j)\nv.map(f => f())    \u002F\u002F [3, 3, 3]\n```\n\nThis per-iteration binding is a deliberate `let` feature that fixes the\nlong-standing closure-in-loop bug.\n",{"id":3080,"difficulty":84,"q":3081,"a":3082},"tdz-typeof","Does typeof protect against the temporal dead zone?","No. `typeof` is safe for **undeclared** identifiers, but a `let`\u002F`const` variable\nin its **TDZ** is declared-but-uninitialized, so even `typeof` throws a\n`ReferenceError`.\n\n```js\ntypeof undeclaredVar  \u002F\u002F 'undefined' (safe)\n\ntypeof x              \u002F\u002F ReferenceError (x is in the TDZ)\nlet x = 1\n```\n\nSo the usual \"use `typeof` to safely check existence\" trick fails for block-scoped\nvariables before their declaration line. The TDZ deliberately makes\nuse-before-declaration an error.\n",{"id":3084,"difficulty":63,"q":3085,"a":3086},"bare-block","What is a bare block and how does it scope variables?","A bare block is a standalone `{ ... }` (not attached to `if`\u002F`for`\u002Fetc.). With\n`let`\u002F`const` it creates a **new block scope**, so variables inside are invisible\noutside — a lightweight way to limit scope. `var` ignores it (function-scoped).\n\n```js\n{\n  let secret = 42\n  var leaked = 1\n}\nconsole.log(leaked) \u002F\u002F 1 (var ignores the block)\nconsole.log(secret) \u002F\u002F ReferenceError (let is block-scoped)\n```\n\nBare blocks can also resolve `switch`\u002Ftemporary-variable naming conflicts by\nisolating declarations.\n",{"id":3088,"difficulty":63,"q":3089,"a":3090},"shadow-nested","Can you shadow a let variable in a nested block?","Yes. A nested block can declare a new `let`\u002F`const` with the same name, creating a\n**separate binding** that shadows the outer one within that block. This is\ndifferent from redeclaration in the **same** scope (which errors).\n\n```js\nlet x = 1\n{\n  let x = 2     \u002F\u002F shadows — different (nested) scope\n  console.log(x) \u002F\u002F 2\n}\nconsole.log(x)  \u002F\u002F 1\n\nlet y = 1\nlet y = 2       \u002F\u002F SyntaxError — same scope\n```\n\nShadowing across scopes is allowed; redeclaring in the same scope is not.\n",{"id":3092,"difficulty":84,"q":3093,"a":3094},"dynamic-vs-lexical","What is the difference between lexical and dynamic scoping?","- **Lexical scoping** (what JS uses): a function's free variables resolve based on\n  **where it's defined** in the source.\n- **Dynamic scoping** (some other languages): free variables resolve based on the\n  **call stack at runtime** — who called the function.\n\n```js\nlet x = 'global'\nfunction inner() { return x }\nfunction outer() { let x = 'outer'; return inner() }\nouter() \u002F\u002F 'global' — lexical: inner sees where it was DEFINED\n\u002F\u002F (a dynamically-scoped language would return 'outer')\n```\n\nJS's only \"dynamic\" feature is `this`, which is bound by the call site — but\nordinary variable lookup is always lexical.\n",{"id":3096,"difficulty":63,"q":3097,"a":3098},"hoisting-mechanism","What actually happens during hoisting (the two phases)?","JavaScript runs in two phases per scope: a **creation (compilation) phase** that\nregisters all declarations (allocating `var` as `undefined`, `let`\u002F`const` as\nuninitialized in the TDZ, functions fully), and an **execution phase** that runs\nthe code and performs assignments in order.\n\n```js\n\u002F\u002F creation phase registers: a (undefined), greet (function)\nconsole.log(a)  \u002F\u002F undefined\nvar a = 1       \u002F\u002F execution: a becomes 1\ngreet()         \u002F\u002F already callable\nfunction greet() {}\n```\n\nSo \"hoisting\" isn't physical code movement — it's declarations being processed\nbefore any line executes. Only assignments happen in place.\n",{"id":3100,"difficulty":63,"q":3101,"a":3102},"var-leak","Why is var leaking out of blocks a problem?","`var` is function-scoped, so a `var` declared inside an `if`\u002F`for`\u002Fblock is visible\nthroughout the **entire enclosing function** — leaking beyond where it's relevant,\nwhich causes accidental reuse and bugs.\n\n```js\nfunction f() {\n  for (var i = 0; i \u003C 3; i++) {}\n  console.log(i) \u002F\u002F 3 — i leaked out of the loop\n\n  if (true) { var temp = 'x' }\n  console.log(temp) \u002F\u002F 'x' — leaked out of the if\n}\n```\n\n`let`\u002F`const` confine variables to their block, keeping scope tight. This leakage\nis a primary reason to avoid `var`.\n",{"id":3104,"difficulty":84,"q":3105,"a":3106},"deep-freeze","How do you make an object deeply immutable?","`Object.freeze` is **shallow** — it freezes the top-level properties but nested\nobjects remain mutable. For deep immutability you must recursively freeze.\n\n```js\nconst obj = Object.freeze({ a: 1, nested: { b: 2 } })\nobj.a = 9          \u002F\u002F ignored (or throws in strict mode)\nobj.nested.b = 99  \u002F\u002F still mutable! freeze is shallow\n\nfunction deepFreeze(o) {\n  Object.values(o).forEach(v => v && typeof v === 'object' && deepFreeze(v))\n  return Object.freeze(o)\n}\n```\n\nCheck frozen status with `Object.isFrozen`. For shared constants, deep-freezing\nprevents accidental mutation.\n",{"id":3108,"difficulty":63,"q":3109,"a":3110},"iife-scope-isolation","How does an IIFE isolate scope?","An IIFE runs immediately and creates a **private function scope**, so variables\ninside never touch the enclosing\u002Fglobal scope. Before block scoping and modules, it\nwas the main tool to avoid polluting globals and to create private state.\n\n```js\n(function () {\n  var temp = 'private'   \u002F\u002F not global\n  \u002F\u002F setup work...\n})()\ntypeof temp \u002F\u002F 'undefined' — isolated\n```\n\nToday, block scope (`{ let ... }`) and ES modules cover most of these needs, but\nIIFEs still appear in bundled code and for one-off encapsulation.\n",{"id":3112,"difficulty":71,"q":3113,"a":3114},"let-vs-const-when","When should you use let vs const?","Default to **`const`** — it signals the binding won't be reassigned, preventing\naccidental reassignment and making code easier to reason about. Use **`let`** only\nwhen you genuinely need to reassign (counters, accumulators, reassigned in\nbranches). Avoid `var`.\n\n```js\nconst MAX = 100          \u002F\u002F never reassigned\nconst user = { id: 1 }   \u002F\u002F const, but you can still mutate the object\nlet total = 0            \u002F\u002F reassigned in a loop\nfor (const item of items) total += item.price\n```\n\n\"const by default, let when needed\" is the widely-adopted convention. Remember\n`const` blocks reassignment, not mutation.\n",{"id":3116,"difficulty":63,"q":3117,"a":3118},"global-pollution","Why are global variables discouraged?","Globals are accessible and mutable from **anywhere**, so they create hidden\ncoupling, name collisions between scripts\u002Flibraries, hard-to-trace bugs, and\nproblems in concurrent\u002Ftesting contexts. Any code can change them unexpectedly.\n\n```js\n\u002F\u002F global state anyone can clobber\nvar config = {}\n\u002F\u002F encapsulate in a module or closure\nexport const config = createConfig()\n```\n\nMinimize globals by using **modules** (module scope), closures, and passing\ndependencies explicitly. When a true global is needed, namespace it under a single\nobject to limit collisions.\n",{"description":61},"Common JavaScript interview questions on var, let and const, scope, hoisting and the temporal dead zone, with clear answers and examples.","javascript\u002Ffundamentals\u002Fvariables-scope-hoisting","Variables, Scope & Hoisting","1OhvPeamj0K5ICmSSBRUFJ9iY7c4aoSeIv0ARSpSdac",{"id":3125,"title":3126,"body":3127,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":3131,"navigation":66,"order":12,"path":3132,"questions":3133,"related":207,"seo":3257,"seoDescription":3258,"stem":3259,"subtopic":3260,"topic":3261,"topicSlug":3262,"updated":214,"__hash__":3263},"qa\u002Fjavascript\u002Fmodern\u002Fdestructuring-spread-rest.md","Destructuring Spread Rest",{"type":58,"value":3128,"toc":3129},[],{"title":61,"searchDepth":22,"depth":22,"links":3130},[],{},"\u002Fjavascript\u002Fmodern\u002Fdestructuring-spread-rest",[3134,3138,3142,3146,3149,3153,3156,3160,3164,3168,3172,3176,3180,3183,3187,3191,3195,3199,3202,3206,3210,3214,3218,3222,3226,3230,3233,3237,3241,3245,3249,3253],{"id":3135,"difficulty":71,"q":3136,"a":3137},"what-is-destructuring","What is destructuring in JavaScript?","**Destructuring** is syntax that unpacks values from objects (or arrays) into\ndistinct variables in a single expression. It replaces repetitive\nproperty-by-property assignment with a compact pattern that mirrors the shape\nof the data.\n\nThe mechanism: the **pattern** on the left of `=` is matched against the\n**value** on the right, binding each name to the corresponding property.\n\n```js\nconst user = { name: 'Ada', age: 36 }\nconst { name, age } = user           \u002F\u002F two variables in one line\nconsole.log(name, age)               \u002F\u002F 'Ada' 36\n\u002F\u002F verbose old way:\n\u002F\u002F const name = user.name; const age = user.age\n```\n\nPitfall: destructuring **reads** properties — it does not mutate the source\nobject. `user` is untouched after the line above.\n",{"id":3139,"difficulty":71,"q":3140,"a":3141},"object-destructuring-basics","How does object destructuring match variables to properties?","It matches **by property name**, not by position (unlike array destructuring).\nThe variable name must equal the key you want to extract.\n\n```js\nconst point = { x: 1, y: 2 }\nconst { y, x } = point               \u002F\u002F order doesn't matter\nconsole.log(x, y)                    \u002F\u002F 1 2\nconst { z } = point                  \u002F\u002F z is undefined (no such key)\n```\n\nPitfall: because matching is by name, a typo silently produces `undefined`\nrather than an error — there is no \"this key doesn't exist\" warning.\n",{"id":3143,"difficulty":71,"q":3144,"a":3145},"rename-while-destructuring","How do you rename a variable while destructuring an object?","Use the `key: newName` syntax. The left side of the colon is the **property to\nread**; the right side is the **local variable** to bind it to.\n\n```js\nconst res = { status: 200, data: 'ok' }\nconst { status: code, data: body } = res   \u002F\u002F rename both\nconsole.log(code, body)                     \u002F\u002F 200 'ok'\n\u002F\u002F console.log(status)                      \u002F\u002F ReferenceError — status not defined\n```\n\nThe original key name (`status`) is **not** in scope afterward — only the new\nname is. Pitfall: people read `status: code` as \"assign status to code\" but it's\nthe reverse — read `status`, name it `code`.\n",{"id":568,"difficulty":71,"q":3147,"a":3148},"How do default values work in object destructuring?","A default after `=` is applied only when the extracted value is **`undefined`**\n(a missing key or an explicit `undefined`). Any other value — including `null`,\n`0`, `''`, or `false` — is kept as-is.\n\n```js\nconst { timeout = 1000, retries = 3 } = { retries: 0 }\nconsole.log(timeout, retries)        \u002F\u002F 1000 0  0 is kept, default not applied\nconst { x = 5 } = { x: null }\nconsole.log(x)                       \u002F\u002F null  default NOT used — null isn't undefined\n```\n\nPitfall: defaults trigger only on `undefined`, so `null` slips through. If you\nneed a fallback for `null` too, combine with `??` after extracting.\n",{"id":3150,"difficulty":63,"q":3151,"a":3152},"rename-and-default","How do you combine renaming and a default value?","Stack the two syntaxes: `key: newName = default`. JavaScript reads `key`,\nbinds it to `newName`, and falls back to `default` if that value is `undefined`.\n\n```js\nconst settings = {}\nconst { mode: displayMode = 'light' } = settings\nconsole.log(displayMode)             \u002F\u002F 'light'  renamed AND defaulted\n```\n\nThe order is fixed: property name, then colon and new name, then equals and\ndefault. Pitfall: writing `mode = 'light': displayMode` is a syntax error — the\ndefault attaches to the renamed binding, after the colon.\n",{"id":991,"difficulty":63,"q":3154,"a":3155},"How do you destructure nested objects?","Nest a pattern wherever a value would be a sub-object. The colon here means\n\"descend into this object\" rather than \"rename\".\n\n```js\nconst user = { name: 'Ada', address: { city: 'London', zip: 'SW1' } }\nconst { address: { city } } = user\nconsole.log(city)                    \u002F\u002F 'London'\n\u002F\u002F console.log(address)              \u002F\u002F ReferenceError — address itself not bound\n```\n\nTwo gotchas: (1) the intermediate name (`address`) is **not** created as a\nvariable — only the leaf (`city`) is. (2) If `address` were `undefined`,\ndestructuring into it throws **`TypeError: Cannot destructure property 'city'\nof undefined`** — add a default: `{ address: { city } = {} }`.\n",{"id":3157,"difficulty":84,"q":3158,"a":3159},"computed-property-destructuring","How do you destructure a property whose key is computed at runtime?","Use **computed key** syntax `[expr]: target`. The bracketed expression is\nevaluated to a string key, and you must supply a binding name after the colon\n(there's no implicit name to infer).\n\n```js\nconst field = 'email'\nconst record = { email: 'a@b.com', name: 'Ada' }\nconst { [field]: value } = record\nconsole.log(value)                   \u002F\u002F 'a@b.com'  dynamic key extracted\n```\n\nPitfall: you **must** name the target (`: value`) — `const { [field] } = record`\nis a syntax error because the engine can't derive a variable name from an\narbitrary expression.\n",{"id":3161,"difficulty":63,"q":3162,"a":3163},"destructuring-params","How do you destructure function parameters?","Put the pattern directly in the parameter list. The caller passes one object and\nthe function pulls out named fields — a common alternative to long positional\nargument lists.\n\n```js\nfunction createUser({ name, role = 'user', active = true }) {\n  return `${name}:${role}:${active}`\n}\ncreateUser({ name: 'Ada', role: 'admin' })   \u002F\u002F 'Ada:admin:true'\n```\n\nThis gives named, order-independent arguments with per-field defaults. Pitfall:\ncalling `createUser()` with **no argument** throws, because you can't destructure\n`undefined`. Guard with a default: `function createUser({ ... } = {})`.\n",{"id":3165,"difficulty":63,"q":3166,"a":3167},"param-default-object","Why give a destructured parameter a default of {}?","Destructuring `undefined` throws a `TypeError`. Defaulting the whole parameter to\n`{}` lets the function be called with **no argument** while still applying each\nfield's individual defaults.\n\n```js\nfunction connect({ host = 'localhost', port = 5432 } = {}) {\n  return `${host}:${port}`\n}\nconnect()                            \u002F\u002F 'localhost:5432' — no throw\n\u002F\u002F without the = {}, connect() would throw TypeError\n```\n\nTwo levels of defaulting are at work: `= {}` guards the missing-object case, and\n`host = ...` \u002F `port = ...` guard missing fields. Pitfall: forgetting the outer\n`= {}` makes the function fragile to no-arg calls.\n",{"id":3169,"difficulty":63,"q":3170,"a":3171},"rest-in-object-destructuring","What does the rest pattern do in object destructuring?","`...rest` collects all **remaining own enumerable** properties not already named\ninto a new object. It's how you extract a few fields and keep the rest grouped.\n\n```js\nconst props = { id: 1, name: 'Ada', role: 'admin' }\nconst { id, ...rest } = props\nconsole.log(id)                      \u002F\u002F 1\nconsole.log(rest)                    \u002F\u002F { name: 'Ada', role: 'admin' }  new object\n```\n\nThe rest object is a **new shallow object**, distinct from the source. Pitfall:\nthe rest element must be **last** — `const { ...rest, id }` is a syntax error.\n",{"id":3173,"difficulty":63,"q":3174,"a":3175},"rest-omit-property","How do you create a copy of an object without a particular property?","Name the property to drop, then capture `...rest`. The named binding is discarded\nand `rest` holds everything else — an immutable \"omit\" pattern.\n\n```js\nconst user = { id: 1, password: 'secret', name: 'Ada' }\nconst { password, ...safe } = user\nconsole.log(safe)                    \u002F\u002F { id: 1, name: 'Ada' }  password removed\n\u002F\u002F user is unchanged — original still has password\n```\n\nThis is purely a copy; the original is untouched. Pitfall: `password` is now an\nunused variable in scope — some linters flag it; an underscore prefix or\n`\u002F\u002F eslint-disable` comment is the usual fix.\n",{"id":3177,"difficulty":71,"q":3178,"a":3179},"object-spread-basics","What does the object spread operator do?","`...obj` inside an object literal copies that object's **own enumerable**\nproperties into the new object. It's the concise way to clone or extend.\n\n```js\nconst base = { a: 1, b: 2 }\nconst copy = { ...base }             \u002F\u002F shallow clone\nconst extended = { ...base, c: 3 }   \u002F\u002F add a property\nconsole.log(extended)                \u002F\u002F { a: 1, b: 2, c: 3 }\n```\n\nSpread only copies **own** enumerable properties — inherited (prototype) and\nnon-enumerable properties are skipped. Pitfall: it's a **shallow** copy, so\nnested objects are shared by reference, not duplicated.\n",{"id":1007,"difficulty":71,"q":3181,"a":3182},"How do you merge two objects with spread?","List both with `...` in one literal. Properties are copied left-to-right, so a\nlater object's values **override** earlier ones for duplicate keys.\n\n```js\nconst defaults = { theme: 'light', size: 'md' }\nconst overrides = { size: 'lg' }\nconst config = { ...defaults, ...overrides }\nconsole.log(config)                  \u002F\u002F { theme: 'light', size: 'lg' }\n```\n\nThe **last write wins** for any shared key. Pitfall: order matters — putting\n`...defaults` last would let defaults clobber your overrides, which is almost\nalways a bug.\n",{"id":3184,"difficulty":63,"q":3185,"a":3186},"spread-override-order","How does property precedence work when spreading and adding keys together?","The object literal is built **left to right**, and each later key with the same\nname overwrites the earlier one. This works whether the key comes from a spread\nor is written literally.\n\n```js\nconst obj = { a: 1 }\nconsole.log({ ...obj, a: 2 })        \u002F\u002F { a: 2 }  literal after spread wins\nconsole.log({ a: 2, ...obj })        \u002F\u002F { a: 1 }  spread after literal wins\n```\n\nPosition, not source type, decides the winner. Pitfall: spreading after your\nexplicit overrides silently undoes them — keep explicit keys after the spreads\nyou want them to win against.\n",{"id":3188,"difficulty":84,"q":3189,"a":3190},"shallow-copy-gotcha","Why is object spread only a shallow copy, and why does that matter?","Spread copies the top-level property **values**. When a value is an object, it\ncopies the **reference**, not a fresh clone — so nested objects are shared\nbetween the original and the copy.\n\n```js\nconst original = { name: 'Ada', meta: { active: true } }\nconst copy = { ...original }\ncopy.meta.active = false\nconsole.log(original.meta.active)    \u002F\u002F false  original mutated too!\ncopy.name = 'Bob'\nconsole.log(original.name)           \u002F\u002F 'Ada'  top-level is independent\n```\n\nTop-level properties are independent; nested ones are not. For a deep copy use\n`structuredClone(original)` (or libraries). Pitfall: mutating nested state on a\n\"copy\" silently corrupts the source — a frequent source of state bugs.\n",{"id":3192,"difficulty":63,"q":3193,"a":3194},"spread-vs-object-assign","What is the difference between spread and Object.assign?","Both do a shallow merge of own enumerable properties, but `Object.assign(target,\n...sources)` **mutates** `target` and returns it, whereas `{ ...a, ...b }`\nalways creates a **new** object.\n\n```js\nconst target = { a: 1 }\nObject.assign(target, { b: 2 })      \u002F\u002F mutates target -> { a: 1, b: 2 }\nconst fresh = { ...target, c: 3 }    \u002F\u002F new object, target untouched\n```\n\nSubtler difference: `Object.assign` **invokes setters** on the target, while\nspread defines plain data properties on a fresh object. Pitfall: passing a real\nobject as `Object.assign`'s first arg unintentionally mutates it — pass `{}`\nfirst (`Object.assign({}, a, b)`) for a non-mutating merge.\n",{"id":3196,"difficulty":84,"q":3197,"a":3198},"spread-with-getters","What happens to getters when you spread an object?","Spread **invokes** each getter and copies its returned value as a plain data\nproperty — the getter itself is not carried over. The copy holds a static\nsnapshot, not a live accessor.\n\n```js\nconst obj = { _n: 1, get n() { return this._n } }\nconst copy = { ...obj }\nobj._n = 99\nconsole.log(copy.n)                  \u002F\u002F 1  frozen snapshot, getter gone\nconsole.log(Object.getOwnPropertyDescriptor(copy, 'n').get)  \u002F\u002F undefined\n```\n\nTo preserve accessors you need `Object.getOwnPropertyDescriptors` +\n`Object.defineProperties`. Pitfall: spreading objects with getters silently\nflattens computed\u002Flazy properties into stale values.\n",{"id":2318,"difficulty":71,"q":3200,"a":3201},"What are rest parameters in a function?","A **rest parameter** (`...args`) collects all remaining arguments into a real\narray. It's the modern, array-native replacement for the `arguments` object.\n\n```js\nfunction sum(...nums) {\n  return nums.reduce((t, n) => t + n, 0)\n}\nsum(1, 2, 3)                         \u002F\u002F 6 — nums is [1, 2, 3]\n```\n\nUnlike `arguments`, `nums` is a genuine `Array` with `map`\u002F`reduce`\u002Fetc., and it\nworks in arrow functions. Pitfall: the rest parameter must be **last** —\n`function f(...a, b)` is a syntax error.\n",{"id":3203,"difficulty":63,"q":3204,"a":3205},"rest-vs-arguments","Why prefer rest parameters over the arguments object?","`arguments` is an **array-like** object — no array methods, and it doesn't exist\nin arrow functions. Rest parameters give a **real array** and work everywhere.\n\n```js\nfunction oldWay() {\n  const args = Array.prototype.slice.call(arguments)  \u002F\u002F awkward conversion\n  return args.map(x => x * 2)\n}\nconst newWay = (...args) => args.map(x => x * 2)       \u002F\u002F clean, works in arrows\n```\n\nRest also makes the signature self-documenting and can capture just the tail\nafter named params. Pitfall: `arguments` reflects all passed args ignoring\nparameter names, which surprises people refactoring to rest.\n",{"id":3207,"difficulty":63,"q":3208,"a":3209},"named-plus-rest-params","How do you combine named parameters with a rest parameter?","List the fixed parameters first, then `...rest` last to gather everything\nbeyond them. The named params consume the leading arguments; the rest collects\nthe tail.\n\n```js\nfunction log(level, ...messages) {\n  console.log(`[${level}]`, messages.join(' '))\n}\nlog('INFO', 'server', 'started')     \u002F\u002F level='INFO', messages=['server','started']\n```\n\n`rest` is empty (`[]`) if no extra arguments are passed — never `undefined`.\nPitfall: rest captures everything after the named params, so you can't place a\nrequired parameter after it.\n",{"id":3211,"difficulty":63,"q":3212,"a":3213},"spread-call-arguments","How do you pass an array as individual function arguments?","Use spread at the **call site**: `fn(...arr)` expands the array elements into\npositional arguments. This replaces the older `fn.apply(null, arr)`.\n\n```js\nconst nums = [3, 1, 4, 1, 5]\nMath.max(...nums)                    \u002F\u002F 5 — same as Math.max(3,1,4,1,5)\n\u002F\u002F Math.max(nums)                    \u002F\u002F NaN — array isn't a number\n```\n\nYou can mix spread with literals: `fn(0, ...nums, 9)`. Pitfall: spreading a very\nlarge array can exceed the engine's argument-count limit and throw `RangeError`.\n",{"id":3215,"difficulty":71,"q":3216,"a":3217},"swap-variables","How do you swap two variables without a temp variable?","Array destructuring lets you assign both sides simultaneously: the right side is\nevaluated into a temporary array, then unpacked back into the variables.\n\n```js\nlet a = 1, b = 2\n;[a, b] = [b, a]                     \u002F\u002F a=2, b=1, no temp needed\n```\n\nThe leading semicolon guards against the previous line being interpreted as a\nfunction call on `[`. Pitfall: forgetting that semicolon when the prior line has\nno `;` causes `2[a, b]` ASI bugs — a classic gotcha.\n",{"id":3219,"difficulty":63,"q":3220,"a":3221},"destructuring-return-values","How does destructuring help with functions that return objects?","A function can return one object and the caller destructures the fields it cares\nabout — order-independent, self-documenting, and easy to extend without breaking\ncallers.\n\n```js\nfunction parse(input) {\n  return { ok: true, value: input.trim(), length: input.length }\n}\nconst { value, ok } = parse('  hi ') \u002F\u002F pick fields by name, any order\n```\n\nAdding a new field to the returned object never breaks existing callers (unlike\nadding a positional array element). Pitfall: if the function can return `null`\n(e.g. a \"not found\" case), destructuring it throws — guard with `?? {}`.\n",{"id":3223,"difficulty":84,"q":3224,"a":3225},"deep-default-in-destructuring","How do nested destructuring and defaults interact when an intermediate is missing?","Each level of a nested pattern can carry its own default. A default on an\n**intermediate** object protects against that object being `undefined` before you\ndescend into it.\n\n```js\nfunction render({ theme: { color = 'black' } = {} } = {}) {\n  return color\n}\nrender()                             \u002F\u002F 'black' — every level defaulted\nrender({ theme: null })              \u002F\u002F TypeError — null isn't undefined, can't destructure\n```\n\nDefaults fire on `undefined` only, so a `null` intermediate still throws. Pitfall:\ncallers passing explicit `null` for a sub-object bypass your `= {}` guard — defend\nwith `?? {}` if `null` is possible.\n",{"id":3227,"difficulty":63,"q":3228,"a":3229},"spread-vs-rest-difference","What is the difference between spread and rest, since both use the ... syntax?","They are mirror images. **Rest collects** multiple items into one\narray\u002Fobject (appears in a parameter list or destructuring pattern). **Spread\nexpands** one iterable\u002Fobject into multiple items (appears in a call, array, or\nobject literal).\n\n```js\nconst [first, ...rest] = [1, 2, 3]   \u002F\u002F rest: collects -> rest = [2, 3]\nconst merged = [first, ...rest]      \u002F\u002F spread: expands -> [1, 2, 3]\n```\n\nRule of thumb: on the **left of `=`** or in **params** it's rest (gathering); on\nthe **right** or inside a literal\u002Fcall it's spread (scattering). Pitfall: same\n`...` token, opposite directions — context decides which.\n",{"id":1015,"difficulty":63,"q":3231,"a":3232},"Can spread be used on things other than arrays?","In an **array literal** or function call, spread works on any **iterable** —\nstrings, `Set`, `Map`, `arguments`, generators. In an **object literal**, spread\nworks on any object's own enumerable properties.\n\n```js\n[...'abc']                           \u002F\u002F ['a', 'b', 'c']  string is iterable\n[...new Set([1, 1, 2])]              \u002F\u002F [1, 2]  dedupe trick\n{ ...{ a: 1 } }                      \u002F\u002F { a: 1 }  object spread\n\u002F\u002F [...{ a: 1 }]                     \u002F\u002F TypeError — plain object isn't iterable\n```\n\nPitfall: object spread and array spread are different mechanisms — a plain object\nis **not** iterable, so `[...obj]` throws even though `{ ...obj }` works.\n",{"id":3234,"difficulty":63,"q":3235,"a":3236},"destructuring-skip-and-rename","How can you destructure and immediately rename a property to avoid a name clash?","Renaming during destructuring sidesteps collisions with existing variables or\nreserved-ish names, and lets you give local, meaningful names.\n\n```js\nconst a = 1\nconst data = { a: 99, default: 'x' }\nconst { a: itemId, default: fallback } = data\nconsole.log(itemId, fallback)        \u002F\u002F 99 'x'  no clash with outer `a`\n```\n\nRenaming also lets you read keys that aren't valid identifiers (like `default`)\ninto usable names. Pitfall: forgetting to rename when a key shadows an in-scope\n`const` causes a redeclaration error.\n",{"id":3238,"difficulty":84,"q":3239,"a":3240},"array-of-objects-destructuring","How do you destructure objects inside an array in one pattern?","Combine array and object patterns: the array pattern picks positions, and each\nelement can itself be an object pattern that picks fields.\n\n```js\nconst users = [{ name: 'Ada' }, { name: 'Bob' }]\nconst [{ name: first }, { name: second }] = users\nconsole.log(first, second)           \u002F\u002F 'Ada' 'Bob'\n```\n\nYou can default a missing element to `{}` to avoid throwing: `[{ name } = {}] =\nusers`. Pitfall: if the array is shorter than the pattern, a missing element is\n`undefined` and destructuring into it throws unless you provide an element\ndefault.\n",{"id":3242,"difficulty":63,"q":3243,"a":3244},"spread-immutable-update","How does spread enable immutable state updates?","Spread the old state and override the changed fields in a new object, leaving the\noriginal untouched — the foundation of immutable updates in Redux, React, etc.\n\n```js\nconst state = { count: 0, user: 'Ada' }\nconst next = { ...state, count: state.count + 1 }\nconsole.log(state.count, next.count) \u002F\u002F 0 1  original preserved\n```\n\nThis makes change detection cheap (reference comparison) and supports\ntime-travel\u002Fundo. Pitfall: it's shallow — updating a **nested** slice requires\nspreading each level (`{ ...state, user: { ...state.user, ... } }`), or nested\nmutations leak into the old state.\n",{"id":3246,"difficulty":84,"q":3247,"a":3248},"default-from-other-param","Can a destructured default reference an earlier-destructured value?","Yes. Defaults are evaluated left to right, so a later field's default can use a\nvalue bound earlier in the same pattern.\n\n```js\nfunction area({ width, height = width } = {}) {\n  return width * height\n}\narea({ width: 5 })                   \u002F\u002F 25 — height defaults to width\n```\n\nThe binding must already be in scope (declared earlier in the pattern). Pitfall:\nreferencing a field declared **after** it throws a temporal-dead-zone\n`ReferenceError` — `{ a = b, b }` fails because `b` isn't initialized yet when\n`a`'s default runs.\n",{"id":3250,"difficulty":63,"q":3251,"a":3252},"spread-null-undefined","What happens when you spread null or undefined?","In an **object** literal, spreading `null` or `undefined` is silently ignored —\nno properties added, no error. In an **array** literal or call, spreading them\n**throws** because they aren't iterable.\n\n```js\nconst o = { ...null, ...undefined, a: 1 }  \u002F\u002F { a: 1 } — ignored safely\n\u002F\u002F const arr = [...null]                    \u002F\u002F TypeError: null is not iterable\n```\n\nThis asymmetry is handy: `{ ...(cond && extra) }` conditionally merges (since\n`false`\u002F`null` spread to nothing). Pitfall: the same `cond && extra` trick in an\n**array** spread throws when the condition is falsy.\n",{"id":3254,"difficulty":63,"q":3255,"a":3256},"rest-shallow-copy","Is the rest object from destructuring a deep or shallow copy?","**Shallow.** The rest pattern builds a new object whose nested values are still\nshared references with the source — only the top-level structure is new.\n\n```js\nconst src = { id: 1, meta: { x: 1 } }\nconst { id, ...rest } = src\nrest.meta.x = 99\nconsole.log(src.meta.x)              \u002F\u002F 99  shared nested reference mutated\n```\n\nSame shallow semantics as object spread (they use the same copy mechanism).\nPitfall: treating the rest object as fully isolated and mutating its nested\nmembers corrupts the original.\n",{"description":61},"JavaScript destructuring, spread and rest interview questions — object destructuring with renaming and defaults, nested and computed keys, object spread for copying and merging, rest parameters, and the shallow-copy gotcha.","javascript\u002Fmodern\u002Fdestructuring-spread-rest","Destructuring, Spread & Rest","Modern JavaScript (ES6+)","modern","j-ktPh8WpFhFjct2cigvLtRd0mYHyPvKzyn8tht5YrQ",{"id":3265,"title":3266,"body":3267,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":3271,"navigation":66,"order":22,"path":3272,"questions":3273,"related":207,"seo":3393,"seoDescription":3394,"stem":3395,"subtopic":3396,"topic":3261,"topicSlug":3262,"updated":214,"__hash__":3397},"qa\u002Fjavascript\u002Fmodern\u002Foptional-chaining-nullish.md","Optional Chaining Nullish",{"type":58,"value":3268,"toc":3269},[],{"title":61,"searchDepth":22,"depth":22,"links":3270},[],{},"\u002Fjavascript\u002Fmodern\u002Foptional-chaining-nullish",[3274,3278,3282,3286,3290,3294,3297,3301,3305,3309,3313,3317,3321,3325,3329,3333,3337,3341,3345,3349,3353,3357,3361,3365,3369,3373,3377,3381,3385,3389],{"id":3275,"difficulty":71,"q":3276,"a":3277},"what-is-optional-chaining","What is optional chaining?","**Optional chaining** (`?.`) accesses a nested property only if the value to its\nleft is **not `null` or `undefined`**; otherwise the whole expression\nshort-circuits and returns `undefined` instead of throwing.\n\n```js\nconst user = { profile: { name: 'Ada' } }\nconsole.log(user.profile?.name)      \u002F\u002F 'Ada'\nconsole.log(user.account?.balance)   \u002F\u002F undefined  no throw\n\u002F\u002F console.log(user.account.balance) \u002F\u002F TypeError: Cannot read 'balance' of undefined\n```\n\nIt replaces long `a && a.b && a.b.c` guards. Pitfall: it guards against `null`\u002F\n`undefined` only — it does **not** protect against other errors like calling a\nnon-function.\n",{"id":3279,"difficulty":71,"q":3280,"a":3281},"optional-chaining-properties","How does ?. work on nested property access?","`a?.b` evaluates `a`; if it's `null`\u002F`undefined` it returns `undefined`,\notherwise it accesses `b`. Chaining several `?.` guards each link in the path.\n\n```js\nconst data = { a: { b: null } }\nconsole.log(data?.a?.b?.c)           \u002F\u002F undefined  stops safely at b being null\n```\n\nImportantly, `?.` only checks the value **immediately to its left**. Pitfall:\n`data.a?.b.c` guards `a` but **not** `b` — if `b` is `null`, accessing `.c`\nstill throws. Put `?.` at every uncertain link.\n",{"id":3283,"difficulty":63,"q":3284,"a":3285},"optional-chaining-methods","How do you optionally call a method that might not exist?","Use `obj.method?.()`. If `method` is `null` or `undefined`, the call is skipped\nand the expression yields `undefined`; otherwise the method runs normally.\n\n```js\nconst api = { log: () => 'logged' }\nconsole.log(api.log?.())             \u002F\u002F 'logged'\nconsole.log(api.track?.())           \u002F\u002F undefined  no track method, no throw\n```\n\nHandy for optional callbacks: `onChange?.(value)`. Pitfall: if `method` exists\nbut is **not a function** (e.g. a number), `?.()` still throws `TypeError: not a\nfunction` — `?.` only guards `null`\u002F`undefined`, not wrong types.\n",{"id":3287,"difficulty":63,"q":3288,"a":3289},"optional-chaining-arrays","How does optional chaining work with array\u002Fdynamic access?","Use `arr?.[index]`. The `?.` before the bracket guards the array itself being\n`null`\u002F`undefined` before the element is read.\n\n```js\nconst result = { items: ['a', 'b'] }\nconsole.log(result.items?.[0])       \u002F\u002F 'a'\nconsole.log(result.tags?.[0])        \u002F\u002F undefined  no tags array, no throw\n```\n\nSame applies to computed keys: `obj?.[key]`. Pitfall: `arr?.[0]` guards `arr`,\nnot the element — if `arr` is `[]`, `arr?.[0]` is `undefined` (fine), but\n`arr?.[0].name` throws because element `0` is `undefined`.\n",{"id":3291,"difficulty":63,"q":3292,"a":3293},"short-circuiting","What does short-circuiting mean in optional chaining?","When `?.` hits a `null`\u002F`undefined`, it **stops evaluating the rest of the\nchain** and returns `undefined` immediately — nothing to the right runs,\nincluding function calls.\n\n```js\nlet calls = 0\nconst obj = null\nconst r = obj?.method(calls++)       \u002F\u002F undefined\nconsole.log(calls)                   \u002F\u002F 0  method() and calls++ never ran\n```\n\nThe entire chain after the short-circuit is skipped, side effects included.\nPitfall: people assume arguments still evaluate — they don't, so relying on a\nside effect inside a short-circuited call is a silent bug.\n",{"id":2921,"difficulty":71,"q":3295,"a":3296},"What is the nullish coalescing operator ??","`a ?? b` returns `a` unless it is **`null` or `undefined`**, in which case it\nreturns `b`. It provides a default only for \"no value\", not for any falsy value.\n\n```js\nconst port = userPort ?? 3000        \u002F\u002F use userPort unless it's null\u002Fundefined\nconsole.log(0 ?? 5)                  \u002F\u002F 0  0 is a real value, kept\nconsole.log(null ?? 5)               \u002F\u002F 5  null -> fallback\n```\n\nIt treats `0`, `''`, `false`, and `NaN` as legitimate values. Pitfall: don't\nreach for `??` when you actually want to reject *all* falsy values — that's `||`.\n",{"id":3298,"difficulty":63,"q":3299,"a":3300},"nullish-vs-or","What is the difference between ?? and ||?","`||` falls back on **any falsy** value (`0`, `''`, `false`, `NaN`, `null`,\n`undefined`). `??` falls back only on **`null`\u002F`undefined`**. The difference\nmatters whenever a falsy value is valid.\n\n```js\nconst count = 0\nconsole.log(count || 10)             \u002F\u002F 10  treats valid 0 as \"missing\"\nconsole.log(count ?? 10)             \u002F\u002F 0   keeps the real 0\nconsole.log('' || 'default')         \u002F\u002F 'default'  empty string lost\nconsole.log('' ?? 'default')         \u002F\u002F ''  empty string kept\n```\n\nUse `??` for defaults of numbers\u002Fstrings\u002Fbooleans. Pitfall: blindly migrating\nevery `||` to `??` (or vice-versa) changes behavior for zero\u002Fempty inputs — a\ncommon subtle regression.\n",{"id":3302,"difficulty":63,"q":3303,"a":3304},"when-to-use-or","When is || still the right choice over ???","Use `||` when you genuinely want **any falsy value** to trigger the fallback —\ne.g. treating empty string, `0`, or `false` the same as \"absent.\"\n\n```js\nconst name = input.name || 'Anonymous'   \u002F\u002F '' should also become Anonymous\nconst items = response.list || []        \u002F\u002F falsy\u002Fempty -> safe default array\n```\n\nHere an empty string genuinely means \"no name,\" so `||` is correct and `??`\nwould let `''` through. Pitfall: the choice is semantic — ask \"is a falsy value a\nlegitimate value here?\" If yes use `??`; if no, `||` is fine.\n",{"id":3306,"difficulty":63,"q":3307,"a":3308},"logical-assignment-nullish","What does the ??= operator do?","`a ??= b` assigns `b` to `a` **only if `a` is currently `null` or `undefined`**.\nIt's shorthand for `a = a ?? b`, but with a key twist: it assigns only when\nneeded.\n\n```js\nconst config = { timeout: 0 }\nconfig.timeout ??= 1000              \u002F\u002F stays 0  (0 isn't nullish)\nconfig.retries ??= 3                 \u002F\u002F becomes 3  (was undefined)\nconsole.log(config)                  \u002F\u002F { timeout: 0, retries: 3 }\n```\n\nIt only writes when the left side is nullish, so existing valid values (even\nfalsy ones) survive. Pitfall: confusing it with `||=`, which would overwrite the\n`0`.\n",{"id":3310,"difficulty":63,"q":3311,"a":3312},"logical-assignment-or","What does ||= do and how does it differ from ??=?","`a ||= b` assigns `b` when `a` is **falsy** (`a = a || b`); `a ??= b` assigns\nonly when `a` is **nullish**. The split mirrors the `||` vs `??` distinction.\n\n```js\nlet x = 0\nx ||= 5                              \u002F\u002F x = 5  overwrote valid 0\nlet y = 0\ny ??= 5                              \u002F\u002F y = 0  kept valid 0\n```\n\nBoth **short-circuit**: if no assignment is needed, the right side never\nevaluates (no side effects, no setter triggered). Pitfall: using `||=` to set a\ndefault on a numeric\u002Fboolean field clobbers legitimate `0`\u002F`false`.\n",{"id":3314,"difficulty":63,"q":3315,"a":3316},"logical-assignment-and","What does the &&= operator do?","`a &&= b` assigns `b` to `a` **only if `a` is truthy** (`a = a && b`). It's used\nto update a value only when it already exists.\n\n```js\nlet user = { name: 'Ada' }\nuser.name &&= user.name.toUpperCase()\nconsole.log(user.name)               \u002F\u002F 'ADA'  updated because it was truthy\nlet empty = null\nempty &&= 'x'                        \u002F\u002F stays null  falsy, left alone\n```\n\nLike the others it short-circuits — `b` only evaluates when `a` is truthy.\nPitfall: it's the least common of the three; people often reach for an `if` when\n`&&=` would read more cleanly (or vice versa where `if` is clearer).\n",{"id":3318,"difficulty":63,"q":3319,"a":3320},"combining-optional-and-nullish","How do you combine ?. with ?? for a safe default?","This is the canonical pair: `?.` safely walks a possibly-missing path and yields\n`undefined`, then `??` supplies a default for that `undefined`.\n\n```js\nconst user = { settings: null }\nconst theme = user?.settings?.theme ?? 'light'\nconsole.log(theme)                   \u002F\u002F 'light'  safe walk + default\n```\n\n`?.` handles the \"path might not exist,\" `??` handles the \"so use a fallback.\"\nPitfall: using `||` instead of `??` here would also override a legitimate\n`theme` of `''` or `0`, which `??` correctly preserves.\n",{"id":3322,"difficulty":84,"q":3323,"a":3324},"precedence-with-nullish","Why must you parenthesize ?? when mixing it with || or &&?","JavaScript **forbids** combining `??` with `||` or `&&` without parentheses — it's\na **syntax error** by design, because the intended precedence is ambiguous to\nreaders.\n\n```js\n\u002F\u002F const x = a || b ?? c             \u002F\u002F SyntaxError\nconst x = (a || b) ?? c              \u002F\u002F explicit grouping required\nconst y = a || (b ?? c)              \u002F\u002F the other grouping\n```\n\nThe language forces you to disambiguate rather than guessing. Pitfall: this is a\ncompile-time error, not a runtime one — copying a clever one-liner from `&&`\u002F`||`\nland into a `??` expression won't even parse.\n",{"id":3326,"difficulty":84,"q":3327,"a":3328},"optional-chaining-not-assignment","Can you use optional chaining on the left side of an assignment?","No. `?.` is only valid for **reading** (and deleting). Using it as an assignment\ntarget is a **syntax error** — you can't conditionally write through it.\n\n```js\nconst obj = { a: {} }\n\u002F\u002F obj?.a?.b = 5                     \u002F\u002F SyntaxError — invalid assignment target\nif (obj?.a) obj.a.b = 5             \u002F\u002F guard, then assign normally\n```\n\n`delete obj?.a.b` is allowed (short-circuits to a no-op if `obj` is nullish), but\nassignment is not. Pitfall: people expect symmetric read\u002Fwrite support and are\nsurprised the parser rejects the assignment form outright.\n",{"id":3330,"difficulty":84,"q":3331,"a":3332},"optional-chaining-overuse","What is the danger of over-using optional chaining?","Sprinkling `?.` everywhere **hides real bugs**. If a value should never be\n`null`, guarding it with `?.` silently swallows the case where it unexpectedly is,\nturning a loud crash into a quiet `undefined` that surfaces far away.\n\n```js\n\u002F\u002F a required user that's accidentally null:\nconst name = user?.profile?.name    \u002F\u002F becomes undefined, no signal something broke\nconst name2 = user.profile.name     \u002F\u002F throws loudly at the actual fault line\n```\n\nUse `?.` only where absence is **legitimate and expected**, not as a blanket\ncrash-suppressor. Pitfall: defensive `?.` everywhere defers the error to a\nconfusing downstream location, making bugs far harder to trace.\n",{"id":3334,"difficulty":84,"q":3335,"a":3336},"nullish-default-vs-destructuring-default","How does ?? differ from a destructuring default?","Both default on `undefined`, but a **destructuring default** does **not** trigger\non `null`, whereas `??` does. So they diverge whenever a value is explicitly\n`null`.\n\n```js\nconst { x = 1 } = { x: null }\nconsole.log(x)                       \u002F\u002F null  \u003C- destructuring default ignores null\nconst y = ({ x: null }).x ?? 1\nconsole.log(y)                       \u002F\u002F 1     \u003C- ?? catches null too\n```\n\nUse a destructuring default for \"missing key,\" and `??` (or both) when `null` is\nalso a \"use the fallback\" signal. Pitfall: assuming `{ x = d }` and `x ?? d`\nbehave identically — they differ precisely on `null`.\n",{"id":3338,"difficulty":63,"q":3339,"a":3340},"optional-call-on-array-method","How do you safely call a method on a possibly-missing array?","Chain `?.` before the method call: `arr?.map(...)`. If `arr` is `null`\u002F\n`undefined`, the whole call short-circuits to `undefined`.\n\n```js\nconst data = {}\nconst upper = data.tags?.map(t => t.toUpperCase())\nconsole.log(upper)                   \u002F\u002F undefined  no throw on missing tags\nconst safe = data.tags?.map(t => t) ?? []  \u002F\u002F fall back to empty array\n```\n\nPair with `?? []` if downstream code expects an array. Pitfall: `data.tags?.map`\nreturning `undefined` will break a chained `.filter()` after it — guard the whole\nchain or supply the `?? []` fallback.\n",{"id":3342,"difficulty":63,"q":3343,"a":3344},"double-question-mark-with-function-call","Does the right-hand side of ?? always evaluate?","No — `??` **short-circuits**. The right operand evaluates **only** when the left\nis `null`\u002F`undefined`. So an expensive default or a function call on the right is\nskipped when the left has a value.\n\n```js\nlet computed = 0\nconst v = 'cached' ?? expensive()    \u002F\u002F expensive() never runs\nfunction expensive() { computed++; return 'x' }\nconsole.log(computed)                \u002F\u002F 0  skipped\n```\n\nThis makes `value ?? buildDefault()` cheap in the common case. Pitfall: relying\non the right side's side effects is a bug, since it may never execute.\n",{"id":3346,"difficulty":84,"q":3347,"a":3348},"chaining-after-optional-call","How does a ?. short-circuit affect the rest of a long chain?","Once any `?.` short-circuits, the **entire remaining chain** — further property\naccesses, calls, and index lookups — is skipped, and the whole expression is\n`undefined`. The short-circuit \"infects\" everything to its right.\n\n```js\nconst obj = { a: null }\nconsole.log(obj.a?.b.c.d())          \u002F\u002F undefined  b.c.d() all skipped\n```\n\nYou don't need `?.` on every link **after** the one that may be nullish — the\nfirst short-circuit covers the rest. Pitfall: but each *independent* uncertain\nlink still needs its own `?.`; the short-circuit only protects links **downstream**\nof where it fired.\n",{"id":3350,"difficulty":71,"q":3351,"a":3352},"nullish-with-numbers","Why is ?? recommended for numeric defaults?","Because `0` is a valid number but **falsy**, `||` would wrongly replace it.\n`??` only replaces `null`\u002F`undefined`, so a real `0` survives.\n\n```js\nconst volume = settings.volume ?? 100   \u002F\u002F volume of 0 stays 0\n\u002F\u002F const bad = settings.volume || 100   \u002F\u002F 0 becomes 100 — muted unmute!\n```\n\nSame reasoning applies to any field where `0`, `''`, or `false` are meaningful.\nPitfall: a \"default to 100\" written with `||` silently breaks the legitimate-zero\ncase — a classic slider\u002Fquantity bug.\n",{"id":3354,"difficulty":84,"q":3355,"a":3356},"optional-chaining-with-this","Does optional chaining preserve the this binding in a method call?","Yes. `obj?.method()` keeps `this` bound to `obj`, exactly like a normal method\ncall — the `?.` only adds the nullish guard, it doesn't change the call's\nreceiver.\n\n```js\nconst counter = {\n  n: 5,\n  get() { return this.n }\n}\nconsole.log(counter?.get())          \u002F\u002F 5  this is still counter\n```\n\nThe short-circuit happens before the call, so `this` is irrelevant when it fires.\nPitfall: extracting the method first (`const g = counter?.get; g()`) **loses**\n`this`, just like without `?.` — optional chaining doesn't bind methods.\n",{"id":3358,"difficulty":63,"q":3359,"a":3360},"nullish-chaining-multiple","How do you chain multiple ?? operators?","`a ?? b ?? c` returns the **first non-nullish** value left to right. It's a clean\nway to express a fallback priority list.\n\n```js\nconst value = userSetting ?? cookieSetting ?? defaultSetting ?? 'fallback'\nconsole.log(null ?? undefined ?? 0)  \u002F\u002F 0  first non-nullish wins (0 counts)\n```\n\nEach `??` short-circuits, so evaluation stops at the first real value. Pitfall:\nthis is valid (chaining `??` with `??` is fine), but mixing in a `||` mid-chain\nwithout parentheses is a syntax error.\n",{"id":3362,"difficulty":84,"q":3363,"a":3364},"optional-delete","Can you use optional chaining with the delete operator?","Yes — `delete obj?.prop` deletes the property if `obj` exists, and is a **no-op**\n(returning `true`) if `obj` is `null`\u002F`undefined`. It's one of the few non-read\ncontexts `?.` allows.\n\n```js\nconst obj = { a: 1 }\ndelete obj?.a                        \u002F\u002F deletes a\nconst nothing = null\ndelete nothing?.x                    \u002F\u002F no-op, no throw\n```\n\nAssignment is still forbidden, but deletion is permitted because it short-circuits\ncleanly. Pitfall: it's an uncommon form, so reviewers may not realize the delete\nis conditionally skipped when the object is nullish.\n",{"id":3366,"difficulty":63,"q":3367,"a":3368},"nullish-assignment-lazy","How is ??= useful for lazy initialization or caching?","Because `??=` only assigns (and only evaluates the right side) when the property is\nnullish, it's perfect for \"compute once and cache\" — subsequent calls skip the\nwork.\n\n```js\nconst cache = {}\nfunction get(key) {\n  return cache[key] ??= expensiveLookup(key)  \u002F\u002F computed once per key\n}\n```\n\nOn the first call `cache[key]` is `undefined`, so the lookup runs and stores;\nlater calls return the cached value without recomputing. Pitfall: if\n`expensiveLookup` can legitimately return `null`\u002F`undefined`, it's treated as\n\"not cached\" and re-runs every time.\n",{"id":3370,"difficulty":63,"q":3371,"a":3372},"optional-chaining-falsy-confusion","Does ?. return undefined or the actual value when the chain succeeds?","When the chain **succeeds**, `?.` returns the real value — it does **not** convert\nanything. It only injects `undefined` when it actually short-circuits on a\nnullish link.\n\n```js\nconst obj = { a: 0, b: false }\nconsole.log(obj?.a)                  \u002F\u002F 0      real value\nconsole.log(obj?.b)                  \u002F\u002F false  real value, not undefined\nconsole.log(obj?.missing)            \u002F\u002F undefined  (short-circuit)\n```\n\nSo a result of `undefined` could mean \"short-circuited\" **or** \"property is\ngenuinely `undefined`.\" Pitfall: you can't distinguish those two cases from the\nresult alone — use `in` or `hasOwnProperty` if the difference matters.\n",{"id":3374,"difficulty":63,"q":3375,"a":3376},"nullish-in-jsx-or-template","Why is ?? safer than || when rendering values in UI?","In templating\u002FJSX, falsy-but-valid values like `0` or `''` should render. `||`\nwould replace them with the fallback, hiding real data; `??` keeps them.\n\n```js\n\u002F\u002F showing a like count:\nconst display = post.likes ?? 'N\u002FA'  \u002F\u002F 0 renders as 0\n\u002F\u002F const bad = post.likes || 'N\u002FA'   \u002F\u002F 0 likes shows 'N\u002FA'\n```\n\nSame for displaying an empty search query or a `false` toggle label. Pitfall:\n`||` in a render path is a frequent source of \"why does zero show as N\u002FA?\" bug\nreports.\n",{"id":3378,"difficulty":63,"q":3379,"a":3380},"optional-chaining-performance","Does optional chaining have meaningful performance cost?","Negligibly. `?.` compiles to a simple `null`\u002F`undefined` check before each\naccess — a tiny conditional. It's far cheaper than the bugs and verbose guards it\nreplaces.\n\n```js\n\u002F\u002F these are essentially equivalent in cost:\nconst a = obj && obj.prop\nconst b = obj?.prop                  \u002F\u002F same check, cleaner\n```\n\nThe \"cost\" worth watching is **semantic**, not CPU — readability and bug-hiding.\nPitfall: don't avoid `?.` for imagined perf reasons; the real concern is using it\nwhere a value should never be nullish (see over-use).\n",{"id":3382,"difficulty":84,"q":3383,"a":3384},"combining-optional-call-and-nullish","How do you safely invoke an optional callback and provide a result default?","Combine `?.()` (skip the call if the function is absent) with `??` (default the\nresult if the call was skipped or returned nullish).\n\n```js\nfunction process(data, transform) {\n  return transform?.(data) ?? data   \u002F\u002F use transform if given, else raw data\n}\nprocess(5)                           \u002F\u002F 5  — no transform, falls back\nprocess(5, x => x * 2)               \u002F\u002F 10 — transform applied\n```\n\n`transform?.(data)` is `undefined` when no callback is passed, and `?? data`\nsupplies the fallback. Pitfall: if `transform` legitimately returns `0`\u002F`''`,\n`??` keeps it (good), but `|| data` would wrongly discard those.\n",{"id":3386,"difficulty":63,"q":3387,"a":3388},"nullish-coalescing-with-assignment-target","Why prefer config.x ??= default over config.x = config.x ?? default?","They're equivalent in result, but `??=` is shorter and, crucially,\n**short-circuits the assignment**: when `config.x` already has a value, no write\nhappens — avoiding spurious setter calls or proxy traps.\n\n```js\n\u002F\u002F verbose:\nconfig.x = config.x ?? compute()\n\u002F\u002F concise + skips the write when x exists:\nconfig.x ??= compute()               \u002F\u002F\n```\n\nFor plain objects the difference is cosmetic; for objects with setters or\nreactive frameworks it avoids unnecessary side effects. Pitfall: on a getter-only\n(read-only) property, `??=` still attempts the write when nullish and throws in\nstrict mode.\n",{"id":3390,"difficulty":84,"q":3391,"a":3392},"optional-chaining-with-bracket-call","How do you combine dynamic key access and optional method calls in one chain?","You can mix `?.[key]` and `?.()` freely in a single chain; each `?.` guards its\nown link, and the first nullish one short-circuits the rest.\n\n```js\nconst handlers = { onSave: () => 'saved' }\nconst name = 'onSave'\nconsole.log(handlers?.[name]?.())    \u002F\u002F 'saved'\nconsole.log(handlers?.['onDelete']?.())  \u002F\u002F undefined  missing handler, no throw\n```\n\nThis pattern safely dispatches to a dynamically-named handler that may not exist.\nPitfall: `handlers[name]?.()` (no `?.` before `[name]`) still throws if\n`handlers` itself is nullish — guard the root too.\n",{"description":61},"JavaScript optional chaining and nullish coalescing interview questions — the ?. operator on properties, methods, and calls, ?? vs ||, logical assignment operators ??= ||= &&=, short-circuiting, and precedence pitfalls.","javascript\u002Fmodern\u002Foptional-chaining-nullish","Optional Chaining & Nullish Coalescing","WX3Bq31uUWq16_jGkIHCQ3CHmeRYaov98DiBBBbqeLY",{"id":3399,"title":3400,"body":3401,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":3405,"navigation":66,"order":40,"path":3406,"questions":3407,"related":207,"seo":3523,"seoDescription":3524,"stem":3525,"subtopic":3400,"topic":3261,"topicSlug":3262,"updated":214,"__hash__":3526},"qa\u002Fjavascript\u002Fmodern\u002Fsymbols.md","Symbols",{"type":58,"value":3402,"toc":3403},[],{"title":61,"searchDepth":22,"depth":22,"links":3404},[],{},"\u002Fjavascript\u002Fmodern\u002Fsymbols",[3408,3412,3416,3420,3424,3428,3432,3436,3440,3444,3448,3452,3455,3459,3463,3467,3471,3475,3479,3483,3487,3491,3495,3499,3503,3507,3511,3515,3519],{"id":3409,"difficulty":71,"q":3410,"a":3411},"what-is-symbol","What is a Symbol?","A **Symbol** is a primitive type (added in ES6) whose every value is\n**guaranteed unique**. You create one by calling `Symbol()`.\n\n```js\nconst a = Symbol()\nconst b = Symbol()\na === b   \u002F\u002F false  always unique, even with no description\ntypeof a  \u002F\u002F 'symbol'\n```\n\nTheir main use is as collision-proof object property keys and as\n\"well-known\" hooks that customize language behavior.\n",{"id":3413,"difficulty":71,"q":3414,"a":3415},"symbol-description","What is the symbol description for?","The optional string passed to `Symbol('desc')` is a **debug label** only —\nit does **not** affect identity. Two symbols with the same description are\nstill different.\n\n```js\nconst s = Symbol('userId')\ns.description   \u002F\u002F 'userId'  read-only label\nSymbol('x') === Symbol('x')   \u002F\u002F false\n```\n\nUse it to make logs and `toString()` output readable; never rely on it for\nequality.\n",{"id":3417,"difficulty":71,"q":3418,"a":3419},"symbol-no-new","Why can't you call Symbol with new?","`Symbol` is **not a constructor** — symbols are primitives, not objects, so\n`new Symbol()` throws a TypeError.\n\n```js\nconst s = Symbol('ok')      \u002F\u002F\nconst bad = new Symbol()    \u002F\u002F TypeError: Symbol is not a constructor\n```\n\nThis deliberately prevents accidental Symbol *wrapper objects*. If you ever\nneed the wrapper, `Object(symbol)` does it, but you rarely should.\n",{"id":3421,"difficulty":63,"q":3422,"a":3423},"symbol-as-key","How do you use a Symbol as an object key?","Use **computed property** syntax (`[sym]`) in a literal, or bracket\nassignment. The key is then accessible only by holding that exact symbol.\n\n```js\nconst id = Symbol('id')\nconst user = { [id]: 123, name: 'Ada' }\nuser[id]    \u002F\u002F 123\nuser.id     \u002F\u002F undefined — 'id' string is a different key\n```\n\nBecause the symbol is unique, this key can never clash with any string key\nor another library's symbol.\n",{"id":3425,"difficulty":63,"q":3426,"a":3427},"symbol-collision-free","Why are symbols useful for avoiding property collisions?","When you attach metadata to objects you don't own (or that mix data from\nmany sources), a symbol key is guaranteed not to overwrite or be overwritten\nby anyone else's key.\n\n```js\nconst CACHE = Symbol('cache')\nfunction memoize(obj) { obj[CACHE] = compute() }  \u002F\u002F won't clash\n```\n\nA string key like `obj.cache` risks stomping a real property; the symbol\ncan't, because no other code holds that symbol.\n",{"id":3429,"difficulty":63,"q":3430,"a":3431},"symbol-not-enumerable","Are symbol-keyed properties enumerable?","Symbol keys are **skipped** by `for...in`, `Object.keys`, `Object.values`,\n`Object.entries`, and `JSON.stringify` — they're effectively hidden from\nordinary enumeration.\n\n```js\nconst s = Symbol('hidden')\nconst o = { [s]: 1, visible: 2 }\nObject.keys(o)       \u002F\u002F ['visible']  symbol omitted\nJSON.stringify(o)    \u002F\u002F '{\"visible\":2}'\n```\n\nThis makes symbols handy for \"internal\" properties that shouldn't leak into\nserialization or iteration.\n",{"id":3433,"difficulty":63,"q":3434,"a":3435},"getownpropertysymbols","How do you retrieve symbol keys from an object?","Use **`Object.getOwnPropertySymbols`**, or `Reflect.ownKeys` to get string\nand symbol keys together.\n\n```js\nconst s = Symbol('id')\nconst o = { [s]: 1, name: 'x' }\nObject.getOwnPropertySymbols(o)  \u002F\u002F [Symbol(id)]\nReflect.ownKeys(o)               \u002F\u002F ['name', Symbol(id)]\n```\n\nSo symbols are **not truly private** — code with a reference to the object\ncan still discover and read them.\n",{"id":3437,"difficulty":63,"q":3438,"a":3439},"symbol-for","What is Symbol.for and the global symbol registry?","**`Symbol.for(key)`** looks up (or creates) a symbol in a process-wide\n**global registry** by string key — so the *same* key always returns the\n*same* symbol, even across modules or realms.\n\n```js\nSymbol.for('app.id') === Symbol.for('app.id')   \u002F\u002F true  shared\nSymbol('app.id')     === Symbol('app.id')        \u002F\u002F false — local\n```\n\nUse `Symbol.for` when different parts of a system must agree on one symbol;\nuse plain `Symbol()` for guaranteed-unique local keys.\n",{"id":3441,"difficulty":63,"q":3442,"a":3443},"symbol-keyfor","What does Symbol.keyFor do?","`Symbol.keyFor(sym)` returns the registry **key string** for a symbol\ncreated via `Symbol.for`, or `undefined` for a non-registered symbol.\n\n```js\nconst g = Symbol.for('shared')\nSymbol.keyFor(g)            \u002F\u002F 'shared'\nSymbol.keyFor(Symbol('x')) \u002F\u002F undefined — not in registry\n```\n\nIt's the inverse of `Symbol.for` and the only way to recover the key of a\nregistered symbol.\n",{"id":3445,"difficulty":63,"q":3446,"a":3447},"well-known-symbols","What are well-known symbols?","They are built-in symbols exposed as static properties on `Symbol` (e.g.\n`Symbol.iterator`, `Symbol.toPrimitive`) that let you **hook into language\noperations** by defining specially-keyed methods on your objects.\n\n```js\nconst range = {\n  [Symbol.iterator]() { \u002F* ... *\u002F }   \u002F\u002F makes object iterable\n}\n```\n\nImplementing the right well-known symbol customizes how your object behaves\nin `for...of`, `instanceof`, type coercion, spreading, and more.\n",{"id":3449,"difficulty":63,"q":3450,"a":3451},"symbol-iterator","How does Symbol.iterator make an object iterable?","Defining a `[Symbol.iterator]()` method that returns an iterator lets your\nobject work with `for...of`, spread, and destructuring.\n\n```js\nconst nums = {\n  *[Symbol.iterator]() { yield 1; yield 2; yield 3 }\n}\n[...nums]   \u002F\u002F [1, 2, 3]\n```\n\nAll built-in iterables (Array, Map, Set, String) implement this symbol — it\nis *the* protocol that makes iteration extensible.\n",{"id":2508,"difficulty":84,"q":3453,"a":3454},"What is Symbol.asyncIterator?","It's the async counterpart of `Symbol.iterator` — defining\n`[Symbol.asyncIterator]()` makes an object usable with **`for await...of`**,\nwhere each `next()` returns a Promise.\n\n```js\nconst stream = {\n  async *[Symbol.asyncIterator]() { yield await fetchChunk() }\n}\nfor await (const chunk of stream) { \u002F* ... *\u002F }   \u002F\u002F\n```\n\nUsed for streams and paginated\u002Fasync data sources where values arrive over\ntime.\n",{"id":3456,"difficulty":84,"q":3457,"a":3458},"symbol-toprimitive","How does Symbol.toPrimitive customize coercion?","Defining `[Symbol.toPrimitive](hint)` lets an object control its conversion\nto a primitive. The `hint` is `'number'`, `'string'`, or `'default'`\ndepending on context.\n\n```js\nconst money = {\n  amount: 5,\n  [Symbol.toPrimitive](hint) {\n    return hint === 'string' ? `$${this.amount}` : this.amount\n  }\n}\n`${money}`   \u002F\u002F '$5'   (string hint)\nmoney * 2    \u002F\u002F 10     (number hint)\n```\n\nIt overrides the default `valueOf`\u002F`toString` dance with a single, precise\nhook.\n",{"id":3460,"difficulty":84,"q":3461,"a":3462},"symbol-tostringtag","What does Symbol.toStringTag control?","It customizes the tag shown by **`Object.prototype.toString`** — the\n`[object X]` label.\n\n```js\nclass Money {\n  get [Symbol.toStringTag]() { return 'Money' }\n}\nObject.prototype.toString.call(new Money())  \u002F\u002F '[object Money]'\n```\n\nBuilt-ins use it too (`[object Map]`, `[object Promise]`). It's mostly for\ndebugging and type-branding, not control flow.\n",{"id":3464,"difficulty":84,"q":3465,"a":3466},"symbol-hasinstance","How can Symbol.hasInstance customize instanceof?","Defining a static `[Symbol.hasInstance](value)` method overrides what\n`value instanceof Class` returns — letting you do duck-typing checks.\n\n```js\nclass Even {\n  static [Symbol.hasInstance](n) { return n % 2 === 0 }\n}\n4 instanceof Even    \u002F\u002F true\n3 instanceof Even    \u002F\u002F false\n```\n\nPowerful but surprising — override `instanceof` sparingly, since readers\nassume it checks the prototype chain.\n",{"id":3468,"difficulty":63,"q":3469,"a":3470},"private-fields-pattern","Are symbols a way to create private properties?","They provide **soft privacy**: symbol keys are hidden from enumeration and\n`JSON.stringify`, so they won't accidentally leak — but anyone with the\nsymbol (or via `Object.getOwnPropertySymbols`) can still access them.\n\n```js\nconst _secret = Symbol('secret')\nclass Vault { constructor() { this[_secret] = 42 } }\n```\n\nFor **hard** privacy use class `#private` fields, which are truly\ninaccessible from outside. Symbols are for collision-avoidance, not\nsecurity.\n",{"id":3472,"difficulty":63,"q":3473,"a":3474},"symbols-and-json","What happens to symbols in JSON.stringify?","Symbol-**keyed** properties are ignored entirely, and a symbol **value**\nbecomes `undefined` (so it's dropped from objects or turned to `null` in\narrays).\n\n```js\nJSON.stringify({ [Symbol('k')]: 1, a: 2 })  \u002F\u002F '{\"a\":2}'  symbol key gone\nJSON.stringify({ a: Symbol('v') })          \u002F\u002F '{}'       symbol value gone\nJSON.stringify([Symbol('v')])               \u002F\u002F '[null]'\n```\n\nSo symbols never survive serialization — keep that in mind for state you\nneed to persist.\n",{"id":3476,"difficulty":71,"q":3477,"a":3478},"symbol-typeof","What does typeof return for a symbol?","**`'symbol'`** — it's its own primitive type alongside string, number,\nboolean, bigint, undefined, and object.\n\n```js\ntypeof Symbol()        \u002F\u002F 'symbol'\ntypeof Symbol.iterator \u002F\u002F 'symbol'\n```\n\nThat distinct `typeof` makes symbols easy to detect, e.g. when guarding a\nfunction that should reject symbol keys.\n",{"id":3480,"difficulty":63,"q":3481,"a":3482},"symbol-to-string-error","Why does implicit string conversion of a symbol throw?","Symbols **don't auto-coerce** to strings to avoid silent bugs — implicit\nconversion (concatenation, template slots) throws a TypeError. You must\nconvert explicitly.\n\n```js\nconst s = Symbol('id')\n'' + s            \u002F\u002F TypeError\n`${s}`            \u002F\u002F TypeError\nString(s)         \u002F\u002F 'Symbol(id)'  explicit\ns.toString()      \u002F\u002F 'Symbol(id)'\n```\n\n`String(sym)` and `.toString()` are the safe, intentional conversions.\n",{"id":3484,"difficulty":84,"q":3485,"a":3486},"symbols-not-cloned","How do symbol keys behave with Object.assign and spread?","They **are** copied — `Object.assign` and object spread copy *enumerable\nown* properties including symbol keys (symbol keys are enumerable for\ncopying purposes even though they're skipped by `for...in`\u002F`Object.keys`).\n\n```js\nconst s = Symbol('id')\nconst src = { [s]: 1, a: 2 }\nconst copy = { ...src }\ncopy[s]   \u002F\u002F 1  symbol key copied\n```\n\nSo spreading does preserve symbol-keyed data — a useful subtlety when you\nassumed they'd be dropped.\n",{"id":3488,"difficulty":63,"q":3489,"a":3490},"symbols-as-constants","Why use symbols for enum-like constants?","Symbols make **unforgeable, collision-free** constants — each is unique, so\nyou can't accidentally match by an equal string literal.\n\n```js\nconst Status = { ACTIVE: Symbol('active'), DONE: Symbol('done') }\nif (task.status === Status.ACTIVE) { \u002F* ... *\u002F }\n```\n\nUnlike string enums, a stray `'active'` elsewhere won't equal\n`Status.ACTIVE`. The tradeoff: symbols don't serialize, so use string enums\nwhen values cross network\u002Fstorage boundaries.\n",{"id":3492,"difficulty":84,"q":3493,"a":3494},"symbol-registry-cross-realm","Why is Symbol.for useful across realms or iframes?","The global registry is shared by string key across **realms** (iframes,\nworker boundaries, modules), so `Symbol.for('x')` yields a matching symbol\neverywhere, whereas a plain `Symbol()` from one realm is unique to it.\n\n```js\n\u002F\u002F iframe A and iframe B both run:\nSymbol.for('app.token')   \u002F\u002F same symbol identity in both\n```\n\nIt's the mechanism for agreeing on a symbol without sharing the actual\nreference.\n",{"id":3496,"difficulty":71,"q":3497,"a":3498},"detect-symbol-support","How do you check if a value is a symbol?","Use `typeof value === 'symbol'`. Avoid `instanceof Symbol`, which is false\nfor primitive symbols.\n\n```js\nconst isSymbol = v => typeof v === 'symbol'\nisSymbol(Symbol())          \u002F\u002F true\nSymbol() instanceof Symbol  \u002F\u002F false primitive, not an instance\n```\n\nThe `typeof` check is the only reliable test for symbol primitives.\n",{"id":3500,"difficulty":84,"q":3501,"a":3502},"well-known-species","What does Symbol.species control?","`Symbol.species` lets a class specify which **constructor** built-in methods\nlike `map`\u002F`filter`\u002F`slice` use to create derived instances.\n\n```js\nclass MyArray extends Array {\n  static get [Symbol.species]() { return Array }  \u002F\u002F map returns Array\n}\nconst r = new MyArray(1, 2, 3).map(x => x)\nr instanceof MyArray   \u002F\u002F false — it's a plain Array\n```\n\nIt's an advanced hook for subclassing built-ins; most code never needs it,\nbut it explains some surprising subclass behaviors.\n",{"id":3504,"difficulty":63,"q":3505,"a":3506},"symbol-iterator-builtin","How do you access the built-in iterator of an array via its symbol?","Call the array's `[Symbol.iterator]()` to get its iterator directly — the\nsame one `for...of` uses.\n\n```js\nconst arr = ['a', 'b']\nconst it = arr[Symbol.iterator]()\nit.next()   \u002F\u002F { value: 'a', done: false }\nit.next()   \u002F\u002F { value: 'b', done: false }\n```\n\nUseful when you want manual control over iteration or to forward an\niterator to other consuming code.\n",{"id":3508,"difficulty":84,"q":3509,"a":3510},"symbols-memory","Do registered symbols cause memory concerns?","Symbols from **`Symbol.for`** live in the global registry for the lifetime\nof the realm and are **never garbage-collected**, since the registry holds\nthem. Plain `Symbol()` values are collectible like any primitive once\nunreferenced.\n\n```js\nSymbol.for('keeps.living')   \u002F\u002F retained globally\nlet s = Symbol('local'); s = null  \u002F\u002F eligible for GC\n```\n\nPrefer plain symbols unless you genuinely need cross-module sharing, to\navoid unbounded registry growth.\n",{"id":3512,"difficulty":63,"q":3513,"a":3514},"symbols-vs-private-fields","When choose symbols over class private fields?","Use **`#private` fields** for true encapsulation within a single class. Use\n**symbols** when you need a non-enumerable key that's shareable across\nmodules, attachable to objects you don't own, or used in mixins.\n\n```js\nclass A { #real = 1 }          \u002F\u002F hard-private, class-scoped\nconst META = Symbol('meta')    \u002F\u002F shareable, attach anywhere\nsomeExternalObj[META] = 'tag'  \u002F\u002F works on foreign objects\n```\n\nPrivacy -> `#`; collision-free extensibility -> symbols.\n",{"id":3516,"difficulty":84,"q":3517,"a":3518},"symbol-default-hint","What is the 'default' hint in Symbol.toPrimitive?","The `'default'` hint is passed for operations that don't clearly want a\nnumber or string — chiefly **`+`** and **`==`** comparisons. You decide\nwhat makes sense.\n\n```js\nconst temp = {\n  c: 20,\n  [Symbol.toPrimitive](hint) {\n    if (hint === 'number') return this.c\n    if (hint === 'string') return `${this.c}°C`\n    return `${this.c}°C`   \u002F\u002F 'default' -> treat like string here\n  }\n}\ntemp + ''   \u002F\u002F '20°C'  (default hint)\n```\n\nMost objects map `'default'` to the same behavior as `'number'` or\n`'string'` depending on intent.\n",{"id":3520,"difficulty":63,"q":3521,"a":3522},"symbols-best-practices","What are best practices for using symbols?","Use plain `Symbol()` for collision-free metadata keys; reserve `Symbol.for`\nfor genuinely shared cross-module symbols; don't treat symbols as a\nsecurity mechanism; and convert to string explicitly with `String(sym)`.\n\n```js\nconst TAG = Symbol('tag')        \u002F\u002F local, unique\nthirdPartyObj[TAG] = 'mine'      \u002F\u002F safe to attach\n```\n\nImplement well-known symbols (`iterator`, `toPrimitive`) when you want\nobjects to integrate with language features — that's where symbols add the\nmost value.\n",{"description":61},"JavaScript Symbol interview questions — unique primitives, the global registry, symbol keys hidden from enumeration, well-known symbols like Symbol.iterator and Symbol.toPrimitive, and metaprogramming use cases.","javascript\u002Fmodern\u002Fsymbols","1lhIA2OYk4Bowpjxzvv-jTPSUsW0Rn_D38uNmRtHFAw",{"id":3528,"title":3529,"body":3530,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":3534,"navigation":66,"order":31,"path":3535,"questions":3536,"related":207,"seo":3656,"seoDescription":3657,"stem":3658,"subtopic":3659,"topic":3261,"topicSlug":3262,"updated":214,"__hash__":3660},"qa\u002Fjavascript\u002Fmodern\u002Ftemplate-literals.md","Template Literals",{"type":58,"value":3531,"toc":3532},[],{"title":61,"searchDepth":22,"depth":22,"links":3533},[],{},"\u002Fjavascript\u002Fmodern\u002Ftemplate-literals",[3537,3541,3545,3549,3553,3557,3561,3565,3569,3573,3577,3581,3585,3589,3593,3597,3601,3605,3609,3613,3617,3621,3625,3629,3633,3637,3641,3645,3649,3653],{"id":3538,"difficulty":71,"q":3539,"a":3540},"template-literal-basics","What is a template literal?","A **template literal** is a string written with **backticks** (`` ` ``)\nthat supports interpolation and spans multiple lines.\n\n```js\nconst name = 'Ada'\nconst msg = `Hello, ${name}!`   \u002F\u002F \"Hello, Ada!\"\n```\n\nBackticks replace the need for string concatenation and make embedded\nvalues far more readable than `'Hello, ' + name + '!'`.\n",{"id":3542,"difficulty":71,"q":3543,"a":3544},"interpolation","How does ${} interpolation work?","Any expression inside **`${ }`** is evaluated and its result coerced to a\nstring, then spliced into place.\n\n```js\nconst a = 5, b = 3\n`Sum is ${a + b}`         \u002F\u002F \"Sum is 8\"\n`Upper: ${name.toUpperCase()}`  \u002F\u002F method calls allowed\n```\n\nIt's a full expression slot — arithmetic, calls, ternaries, even nested\ntemplate literals all work. It is **not** a statement slot, so `if`\u002F`for`\ncan't go there.\n",{"id":3546,"difficulty":71,"q":3547,"a":3548},"multiline-strings","How do template literals handle multiline strings?","Newlines inside backticks are **preserved literally** — no `\\n` or\nconcatenation needed.\n\n```js\nconst text = `Line 1\nLine 2`         \u002F\u002F contains a real newline\n```\n\nPitfall: indentation inside the literal becomes part of the string. Leading\nspaces on the second line are included, which can surprise you when the\ncode is nested deep in a function.\n",{"id":3550,"difficulty":63,"q":3551,"a":3552},"expression-embedding","What kinds of expressions can you embed?","Any valid JavaScript **expression**: arithmetic, function calls, ternaries,\nproperty access, even another template literal.\n\n```js\n`Status: ${active ? 'on' : 'off'}`\n`Total: ${items.reduce((s, i) => s + i.price, 0)}`   \u002F\u002F\n```\n\nKeep them simple, though — heavy logic inside `${}` hurts readability.\nCompute into a variable first when the expression gets complex.\n",{"id":3554,"difficulty":63,"q":3555,"a":3556},"nested-templates","Can you nest template literals?","Yes — a `${}` slot can contain another backtick string, which is useful for\nconditional fragments.\n\n```js\nconst html = `\u003Cul>${items.map(i => `\u003Cli>${i}\u003C\u002Fli>`).join('')}\u003C\u002Ful>`\n```\n\nIt works, but deeply nested templates become hard to read. For non-trivial\nmarkup, prefer a templating library or break the pieces into named\nvariables.\n",{"id":3558,"difficulty":63,"q":3559,"a":3560},"tagged-template-basics","What is a tagged template?","A **tagged template** calls a function with the literal's parts. The tag\nfunction receives the array of **string segments** first, then each\ninterpolated **value** as subsequent arguments.\n\n```js\nfunction tag(strings, ...values) {\n  return { strings, values }\n}\ntag`Hi ${name}, you are ${age}`\n\u002F\u002F strings: ['Hi ', ', you are ', ''], values: [name, age]\n```\n\nThe tag fully controls the output — it doesn't have to return a string at\nall. This powers libraries like styled-components and graphql-tag.\n",{"id":3562,"difficulty":63,"q":3563,"a":3564},"tagged-template-strings-values","Why does the strings array always have one more element than values?","Because the string segments **surround** the interpolations — there's\nalways a piece before the first `${}` and after the last one (possibly\nempty).\n\n```js\ntag`a${1}b${2}c`\n\u002F\u002F strings: ['a', 'b', 'c']  (3)\n\u002F\u002F values:  [1, 2]           (2)  strings.length === values.length + 1\n```\n\nTag functions rely on this invariant to interleave: zip\n`strings[i]` with `values[i]` and append the final `strings[n]`.\n",{"id":3566,"difficulty":63,"q":3567,"a":3568},"string-raw","What does String.raw do?","**`String.raw`** is a built-in tag that returns the string with escape\nsequences **uninterpreted** — backslashes stay literal.\n\n```js\nString.raw`C:\\new\\test`   \u002F\u002F 'C:\\\\new\\\\test' (backslashes kept)\n`C:\\new\\test`             \u002F\u002F 'C:' + newline + 'ew' + tab + 'est'\n```\n\nGreat for Windows paths, regex source, and LaTeX. The `strings.raw`\nproperty is how any custom tag accesses the un-escaped segments.\n",{"id":3570,"difficulty":84,"q":3571,"a":3572},"raw-property","What is the .raw property on the strings array?","Inside a tag, `strings` also carries a **`raw`** array holding the\nsegments **before** escape processing — so the tag can choose cooked or raw\ntext.\n\n```js\nfunction show(strings) {\n  return strings.raw[0]   \u002F\u002F raw, e.g. '\\\\n' stays as backslash-n\n}\nshow`\\n`   \u002F\u002F '\\\\n'  not an actual newline\n```\n\n`String.raw` is literally implemented by joining `strings.raw` with the\nvalues.\n",{"id":3574,"difficulty":63,"q":3575,"a":3576},"i18n-use-case","How are tagged templates used for internationalization?","A tag can rebuild the message from its parts, looking up a translated\ntemplate by the static `strings` segments and re-inserting the dynamic\nvalues.\n\n```js\nfunction i18n(strings, ...values) {\n  const key = strings.join('{}')          \u002F\u002F stable lookup key\n  const translated = dictionary[key] ?? key\n  return interpolate(translated, values)   \u002F\u002F locale-aware\n}\ni18n`Hello ${name}`\n```\n\nBecause the static parts are constant per call site, they make a reliable\ntranslation key.\n",{"id":3578,"difficulty":84,"q":3579,"a":3580},"html-escaping-tag","How can a tagged template prevent injection?","The tag escapes the **interpolated values** while leaving the static\n`strings` (trusted, author-written) untouched — exactly what raw template\nliterals fail to do.\n\n```js\nfunction safeHtml(strings, ...values) {\n  return strings.reduce((out, s, i) =>\n    out + s + (i \u003C values.length ? escapeHtml(values[i]) : ''), '')\n}\nsafeHtml`\u003Cp>${userInput}\u003C\u002Fp>`   \u002F\u002F userInput is escaped\n```\n\nThis is the secure pattern; plain `` `\u003Cp>${userInput}\u003C\u002Fp>` `` injects raw\nuser input.\n",{"id":3582,"difficulty":84,"q":3583,"a":3584},"injection-risk","What's the security pitfall of plain template literals?","They perform **no escaping** — interpolated values go in verbatim. Building\nHTML or SQL by interpolation invites XSS\u002FSQL injection.\n\n```js\nel.innerHTML = `\u003Cdiv>${userInput}\u003C\u002Fdiv>`   \u002F\u002F XSS if userInput has \u003Cscript>\ndb.query(`SELECT * FROM u WHERE id = ${id}`) \u002F\u002F SQL injection\n```\n\nUse a sanitizing tag for HTML, and **parameterized queries** for SQL —\nnever interpolate untrusted data into markup or queries directly.\n",{"id":3586,"difficulty":71,"q":3587,"a":3588},"concatenation-comparison","Why prefer template literals over string concatenation?","They're more readable, avoid `+` clutter and stray-space bugs, and handle\nmultiline naturally.\n\n```js\n'Hi ' + name + ', you have ' + n + ' items'   \u002F\u002F noisy\n`Hi ${name}, you have ${n} items`             \u002F\u002F clear\n```\n\nConcatenation also silently coerces with `+`, where a misplaced operand can\nproduce `NaN` or \"[object Object]\"; template slots make intent explicit.\n",{"id":3590,"difficulty":63,"q":3591,"a":3592},"coercion-in-template","How are non-string values coerced inside a template?","Each `${}` result is converted with the abstract ToString — objects call\n`toString()`, arrays join with commas, `null`\u002F`undefined` stringify\nliterally.\n\n```js\n`${[1, 2, 3]}`    \u002F\u002F '1,2,3'\n`${ {a: 1} }`     \u002F\u002F '[object Object]'  rarely what you want\n`${null}`         \u002F\u002F 'null'\n```\n\nFor objects you usually want `JSON.stringify(obj)` inside the slot rather\nthan relying on the default `[object Object]`.\n",{"id":3594,"difficulty":71,"q":3595,"a":3596},"escaping-backtick","How do you include a backtick or ${ literally?","Escape them with a backslash.\n\n```js\n`A backtick: \\``        \u002F\u002F \"A backtick: `\"\n`Not a slot: \\${x}`     \u002F\u002F \"Not a slot: ${x}\"  literal\n```\n\nWithout the backslash, `${x}` would be interpreted as interpolation. This\nmatters when generating template-literal source code or documentation.\n",{"id":3598,"difficulty":63,"q":3599,"a":3600},"css-in-js","How do tagged templates enable CSS-in-JS?","Libraries like styled-components expose a tag that turns the literal into a\nstyled component, injecting interpolated values as dynamic style props.\n\n```js\nconst Button = styled.button`\n  color: ${props => props.primary ? 'white' : 'black'};\n`   \u002F\u002F tag processes the CSS + functions\n```\n\nThe tag receives the CSS chunks and the prop-accessor functions, then\ngenerates real stylesheets at render time.\n",{"id":3602,"difficulty":63,"q":3603,"a":3604},"graphql-gql","Why does GraphQL use a gql tagged template?","The `gql` tag parses the query string into an **AST** at definition time,\ncatching syntax errors early and enabling tooling (highlighting, type\ngeneration) on the embedded query.\n\n```js\nconst QUERY = gql`\n  query { user { id name } }\n`   \u002F\u002F parsed, not just a string\n```\n\nIt also lets fragments be interpolated and composed via `${}` while keeping\na single parse step.\n",{"id":3606,"difficulty":84,"q":3607,"a":3608},"performance-static-strings","Are the strings arrays in tagged templates cached?","Yes — for a given tagged-template **call site**, the engine reuses the\n**same frozen `strings` array** across invocations. This lets tags memoize\nby identity.\n\n```js\nfunction tag(strings) { \u002F* strings is the same object each call *\u002F }\nfunction run() { return tag`hello` }\nrun() ; run()   \u002F\u002F both calls receive the identical strings reference\n```\n\nLibraries exploit this to cache parsed templates (e.g. compiled CSS or\nGraphQL) keyed on the `strings` object.\n",{"id":3610,"difficulty":63,"q":3611,"a":3612},"dedent-indentation","How do you handle unwanted indentation in multiline templates?","The literal preserves source indentation, so nested code leaks leading\nspaces. Use a **dedent** tag or post-process with a regex.\n\n```js\nconst sql = `\n  SELECT *\n  FROM users\n`   \u002F\u002F each line has leading spaces\n\nconst clean = sql.replace(\u002F^\\s+\u002Fgm, '')   \u002F\u002F strip leading whitespace\n```\n\nDedent helper tags are common in test fixtures and embedded SQL\u002FGraphQL to\nkeep output clean while keeping source readable.\n",{"id":3614,"difficulty":71,"q":3615,"a":3616},"ternary-in-slot","How do you add conditional content inside a template?","Use a **ternary** or short-circuit expression in the slot — statements\naren't allowed.\n\n```js\n`Cart${count !== 1 ? 's' : ''}`           \u002F\u002F pluralize\n`${error ? `Error: ${error}` : 'OK'}`     \u002F\u002F nested + conditional\n```\n\nFor anything beyond a simple ternary, compute the fragment in a variable\nfirst to keep the literal readable.\n",{"id":3618,"difficulty":63,"q":3619,"a":3620},"arrays-join-in-template","How do you render a list inside a template literal?","Map to strings and **`join`** — relying on default array coercion adds\ncommas you usually don't want.\n\n```js\n`\u003Cul>${items.map(i => `\u003Cli>${i}\u003C\u002Fli>`).join('')}\u003C\u002Ful>`   \u002F\u002F\n`\u003Cul>${items}\u003C\u002Ful>`   \u002F\u002F inserts commas between items\n```\n\nThe explicit `.join('')` (or `.join(', ')`) controls the separator instead\nof getting the implicit comma.\n",{"id":3622,"difficulty":63,"q":3623,"a":3624},"template-vs-format","Do template literals support format specifiers like printf?","No — there's no `%d`\u002F`%s` formatting. You format inside the slot with\nmethods or `Intl`.\n\n```js\n`Price: ${value.toFixed(2)}`                       \u002F\u002F 2 decimals\n`Date: ${new Intl.DateTimeFormat('en').format(d)}` \u002F\u002F locale format\n```\n\nFor padding\u002Fnumber formatting use `padStart`, `toLocaleString`, or `Intl.*`\nrather than expecting printf-style directives.\n",{"id":3626,"difficulty":71,"q":3627,"a":3628},"empty-interpolation","What happens with an empty or whitespace ${} slot?","`${}` with nothing is a **SyntaxError** — a slot must contain an\nexpression. Whitespace alone is also invalid.\n\n```js\n`${}`        \u002F\u002F SyntaxError\n`${ '' }`    \u002F\u002F an empty-string expression is fine\n`${ \u002F* x *\u002F undefined }`  \u002F\u002F valid, inserts 'undefined'\n```\n\nYou need a real expression; if you want nothing, interpolate an empty\nstring `''`.\n",{"id":3630,"difficulty":84,"q":3631,"a":3632},"tagged-non-string-return","Can a tagged template return something other than a string?","Yes — the tag's return value is whatever the function returns. It can be an\nobject, a component, a parsed AST, a function, anything.\n\n```js\nfunction obj(strings, ...values) {\n  return { template: strings, data: values }   \u002F\u002F returns an object\n}\nconst x = obj`a ${1}`   \u002F\u002F x is an object, not a string\n```\n\nThis flexibility is the whole point — tags are a DSL hook, not just string\nformatters.\n",{"id":3634,"difficulty":63,"q":3635,"a":3636},"line-continuation","How do you write a long single-line string without a literal newline?","End a line with a **backslash** to continue without inserting a newline.\n\n```js\nconst s = `This is one long \\\nlogical line`   \u002F\u002F no newline between 'long ' and 'logical'\n```\n\nBe careful: any spaces after the backslash break it. This is occasionally\nhandy, but joining string parts or using normal wrapping is usually\nclearer.\n",{"id":3638,"difficulty":63,"q":3639,"a":3640},"template-with-functions","Can you call a function and use its result in a slot?","Yes — slots are expressions, so calls (including IIFEs) are allowed and\ntheir return value is interpolated.\n\n```js\n`Now: ${getTime()}`\n`Result: ${(() => compute())()}`   \u002F\u002F IIFE result\n```\n\nSide effects run at interpolation time, in left-to-right order with the\nother slots — keep that in mind if a slot mutates state.\n",{"id":3642,"difficulty":63,"q":3643,"a":3644},"comparison-with-sprintf","When might you still want a formatting library instead of templates?","For locale-aware numbers\u002Fdates, complex pluralization (ICU MessageFormat),\nor printf-style alignment, dedicated libraries (`Intl`, `messageformat`) do\nwhat raw templates can't.\n\n```js\n\u002F\u002F pluralization rules vary by language — a template can't express them all\nmessageFormat.format({ count })   \u002F\u002F handles one\u002Ffew\u002Fmany per locale\n```\n\nTemplates excel at simple interpolation and embedded DSLs; reach for\nformatting libs when human-language or numeric formatting gets involved.\n",{"id":3646,"difficulty":63,"q":3647,"a":3648},"jsx-relation","Are template literals related to JSX?","No — JSX is a separate compile-time syntax transformed by Babel\u002FTypeScript,\nnot a runtime template literal. But tagged templates (`html\\`...\\``) are\nthe **JSX-free** alternative used by libraries like lit-html.\n\n```js\n\u002F\u002F lit-html: tagged template, no build step needed\nhtml`\u003Cdiv>${content}\u003C\u002Fdiv>`   \u002F\u002F runtime, parsed by the html tag\n```\n\nSo tagged templates give a \"JSX-like\" templating experience without a\ncompiler.\n",{"id":3650,"difficulty":84,"q":3651,"a":3652},"whitespace-control","How do you control whitespace between interpolations?","Whatever sits between `${}` slots in the source is kept exactly, so you\nmanage spacing by what you type — or strip it in a tag.\n\n```js\n`${a} ${b}`     \u002F\u002F single space between\n`${a}${b}`      \u002F\u002F no space\n`${a}\n${b}`           \u002F\u002F newline preserved between them\n```\n\nFor HTML where whitespace collapses anyway it rarely matters; for\nprecise output (CSV, fixed-width), a normalizing tag gives full control.\n",{"id":464,"difficulty":71,"q":3654,"a":3655},"What are best practices for template literals?","Keep `${}` expressions simple, never interpolate untrusted data into\nHTML\u002FSQL without escaping\u002Fparameters, use `String.raw` for paths\u002Fregex, and\nmind leaked indentation in multiline strings.\n\n```js\nconst label = `${count} ${count === 1 ? 'item' : 'items'}`  \u002F\u002F simple\nel.textContent = `Hello ${name}`   \u002F\u002F textContent, not innerHTML\n```\n\nPrefer `textContent` over `innerHTML`, and a sanitizing tag when raw markup\nis unavoidable.\n",{"description":61},"JavaScript template literal interview questions — interpolation, multiline strings, expression embedding, tagged templates, String.raw and security pitfalls around escaping.","javascript\u002Fmodern\u002Ftemplate-literals","Template Literals & Tagged Templates","omSaAPQVGjJbVBYUSbK9SnLVjjpYF_CcFJGLpbxUZSU",{"id":3662,"title":3663,"body":3664,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":3668,"navigation":66,"order":40,"path":3669,"questions":3670,"related":207,"seo":3771,"seoDescription":3772,"stem":3773,"subtopic":3774,"topic":3775,"topicSlug":3776,"updated":214,"__hash__":3777},"qa\u002Fjavascript\u002Fobjects\u002Fnew-constructors.md","New Constructors",{"type":58,"value":3665,"toc":3666},[],{"title":61,"searchDepth":22,"depth":22,"links":3667},[],{},"\u002Fjavascript\u002Fobjects\u002Fnew-constructors",[3671,3675,3679,3683,3687,3691,3695,3699,3703,3707,3711,3715,3719,3723,3727,3731,3735,3739,3743,3747,3751,3755,3759,3763,3767],{"id":3672,"difficulty":63,"q":3673,"a":3674},"what-does-new-do","What does the new operator do?","`new Fn(args)` performs four steps:\n\n1. Creates a fresh empty object.\n2. Sets that object's prototype to `Fn.prototype`.\n3. Calls `Fn` with `this` bound to the new object.\n4. Returns the new object — unless `Fn` explicitly returns its own object.\n\n```js\nfunction User(name) { this.name = name }\nconst u = new User('Ada')\n\u002F\u002F roughly:\n\u002F\u002F const u = Object.create(User.prototype)\n\u002F\u002F User.call(u, 'Ada')\n```\n\nThose four steps are the whole \"magic\" of `new`. Understanding them explains\n`this`, the prototype link, and the return-value rules below.\n",{"id":3676,"difficulty":71,"q":3677,"a":3678},"constructor-function","What is a constructor function?","A regular function intended to be called with `new` to create objects. By\nconvention its name is **capitalized**. Inside, `this` is the new instance.\n\n```js\nfunction Point(x, y) {\n  this.x = x\n  this.y = y\n}\nconst p = new Point(1, 2)   \u002F\u002F { x: 1, y: 2 }\n```\n\nThere's nothing special about the function itself — any function can be a\nconstructor. The capitalization is a signal to callers that it must be invoked\nwith `new`. Classes are the modern replacement.\n",{"id":3680,"difficulty":84,"q":3681,"a":3682},"forget-new","What happens if you forget new on a constructor function?","Without `new`, the function runs as a plain call: `this` is `undefined` (strict)\nor the global object (sloppy), so it doesn't create an instance — and in sloppy\nmode it leaks properties onto the global object.\n\n```js\nfunction User(name) { this.name = name }\nconst u = User('Ada')   \u002F\u002F no new\nu                       \u002F\u002F undefined (function returns nothing)\n\u002F\u002F sloppy mode: created a global `name`!\n```\n\nGuards: use a `class` (which throws if called without `new`), or check\n`new.target`\u002F`instanceof` and re-invoke with `new`. This bug is exactly why\nclasses enforce `new`.\n",{"id":3684,"difficulty":84,"q":3685,"a":3686},"return-from-constructor","What happens when a constructor returns a value?","If a constructor returns an **object**, that object replaces the newly created\n`this`. If it returns a **primitive** (or nothing), the primitive is ignored and\n`this` is returned as usual.\n\n```js\nfunction A() { this.x = 1; return { y: 2 } }\nnew A()   \u002F\u002F { y: 2 } — object return overrides `this`\n\nfunction B() { this.x = 1; return 42 }\nnew B()   \u002F\u002F { x: 1 } — primitive return ignored\n```\n\nThis \"return an object to override\" behavior enables some factory tricks but is\nusually a footgun — most constructors return nothing.\n",{"id":3688,"difficulty":84,"q":3689,"a":3690},"new-target","What is new.target?","A meta-property that is the constructor invoked with `new`, or `undefined` for a\nnormal call. It lets a function detect how it was called.\n\n```js\nfunction User(name) {\n  if (!new.target) throw new Error('User must be called with new')\n  this.name = name\n}\nUser('Ada')      \u002F\u002F throws\nnew User('Ada')  \u002F\u002F\n```\n\nIn a class hierarchy, `new.target` is the actual subclass being constructed —\nuseful for abstract base classes and for factory logic that varies by concrete\ntype.\n",{"id":3692,"difficulty":63,"q":3693,"a":3694},"new-and-prototype","How does new connect an instance to its prototype?","`new Fn()` sets the instance's prototype to `Fn.prototype`, so the instance\ninherits everything defined there.\n\n```js\nfunction Dog() {}\nDog.prototype.bark = () => 'woof'\nconst d = new Dog()\nObject.getPrototypeOf(d) === Dog.prototype  \u002F\u002F true\nd.bark()                                      \u002F\u002F 'woof' (inherited)\n```\n\nThat's why methods go on `Fn.prototype` — every `new` instance shares them via\nthe prototype link. Reassigning `Fn.prototype` after creating an instance\ndoesn't change that instance's prototype.\n",{"id":3696,"difficulty":63,"q":3697,"a":3698},"constructor-vs-factory","What is the difference between a constructor and a factory function?","- A **constructor** is used with `new`, relies on `this`, and links instances to\n  a shared prototype.\n- A **factory** is a normal function that **returns** an object (no `new`, no\n  `this`), often using closures for privacy and composition for behavior.\n\n```js\nfunction User(name) { this.name = name }       \u002F\u002F constructor -> new User()\nfunction createUser(name) { return { name } }   \u002F\u002F factory -> createUser()\n```\n\nFactories avoid `new`\u002F`this` pitfalls and offer closure-based privacy;\nconstructors\u002Fclasses share methods via the prototype (more memory-efficient for\nmany instances). Both are valid.\n",{"id":3700,"difficulty":63,"q":3701,"a":3702},"this-in-constructor","What is this inside a constructor?","When called with `new`, `this` is the brand-new instance being created, so\nassignments to `this.x` become the object's own properties.\n\n```js\nfunction Account(balance) {\n  this.balance = balance       \u002F\u002F own property of the new instance\n  this.deposit = function (n) { this.balance += n }\n}\n```\n\nCalled **without** `new`, `this` follows normal rules (undefined\u002Fglobal), which\nis the source of the \"forgot new\" bug. Inside a class constructor, `this` is the\ninstance (and is `undefined` until `super()` runs in a subclass).\n",{"id":3704,"difficulty":63,"q":3705,"a":3706},"constructor-property-instance","How do you find which constructor created an object?","Use `instance.constructor` (inherited from the prototype) or `instanceof`.\n\n```js\nfunction User() {}\nconst u = new User()\nu.constructor === User        \u002F\u002F true\nu.constructor.name            \u002F\u002F 'User'\nu instanceof User             \u002F\u002F true\n```\n\n`constructor` is informational and can be wrong if the prototype was replaced\nwithout restoring it. For reliable type checks, prefer `instanceof` (or\nduck-typing), not the `constructor` property.\n",{"id":3708,"difficulty":71,"q":3709,"a":3710},"built-in-constructors","What are the built-in constructors?","JavaScript provides constructors for its core types: `Object`, `Array`,\n`Function`, `Date`, `RegExp`, `Map`, `Set`, `Promise`, `Error`, and the wrapper\nconstructors `String`\u002F`Number`\u002F`Boolean`.\n\n```js\nnew Date()\nnew Map()\nnew Error('boom')\nnew Array(3)        \u002F\u002F [ \u003C3 empty items> ] — quirky\n```\n\nMost are used with `new`, though some (like `Array`, `Object`) also work without\nit. **Avoid** `new String\u002FNumber\u002FBoolean` — they create wrapper *objects* that\nbreak `===` and are always truthy.\n",{"id":3712,"difficulty":63,"q":3713,"a":3714},"array-constructor-pitfall","What is the pitfall of the Array constructor?","`new Array(n)` with a **single number** creates an empty array of length `n`\n(holes), not an array containing `n`. With multiple args it creates an array of\nthose elements.\n\n```js\nnew Array(3)        \u002F\u002F [ \u003C3 empty items> ] — length 3, no values\nnew Array(1, 2, 3)  \u002F\u002F [1, 2, 3]\nArray.of(3)         \u002F\u002F [3] — the unambiguous alternative\nArray.from({length: 3}, (_, i) => i)  \u002F\u002F [0, 1, 2]\n```\n\nThis inconsistency is why `Array.of` exists and why array literals `[]` are\npreferred. The \"empty items\" are holes, which behave oddly with iteration.\n",{"id":3716,"difficulty":63,"q":3717,"a":3718},"instanceof-check","How does instanceof relate to constructors?","`obj instanceof Ctor` is true when `Ctor.prototype` is in `obj`'s prototype\nchain — i.e. `obj` was (effectively) built by `Ctor` or a subclass.\n\n```js\nconst d = new Date()\nd instanceof Date    \u002F\u002F true\nd instanceof Object  \u002F\u002F true (Object.prototype is in the chain)\n```\n\nIt checks the prototype chain, not the literal constructor used, so it sees\ninheritance. It can be fooled by reassigned prototypes and fails across realms —\nuse `Array.isArray` \u002F `Object.prototype.toString` for those cases.\n",{"id":3720,"difficulty":84,"q":3721,"a":3722},"super-in-constructor","Why must super() be called before this in a subclass constructor?","In a derived class, the instance (`this`) is created by the **parent**\nconstructor, so you must call `super()` first to initialize it. Accessing `this`\nbefore `super()` throws a `ReferenceError`.\n\n```js\nclass Animal { constructor(name) { this.name = name } }\nclass Dog extends Animal {\n  constructor(name) {\n    this.bark = true     \u002F\u002F ReferenceError — before super()\n    super(name)\n    this.bark = true     \u002F\u002F\n  }\n}\n```\n\nThis is a real difference from constructor functions, where `this` exists\nimmediately. The rule guarantees the parent has set up the object before the\nchild touches it.\n",{"id":3724,"difficulty":84,"q":3725,"a":3726},"singleton-constructor","How can a constructor enforce a singleton?","Cache the instance and return it on subsequent `new` calls — leveraging the\n\"return an object overrides this\" rule.\n\n```js\nclass Config {\n  constructor() {\n    if (Config.instance) return Config.instance\n    Config.instance = this\n  }\n}\nnew Config() === new Config()   \u002F\u002F true — same instance\n```\n\nBecause returning an object from a constructor replaces the new `this`, the\nsecond `new` gets the cached instance. (A module-level singleton or a frozen\nobject is often simpler.)\n",{"id":3728,"difficulty":63,"q":3729,"a":3730},"prototype-methods-vs-constructor","Should methods go in the constructor or on the prototype?","Put **methods on the prototype** (shared, one copy); put **per-instance data**\nin the constructor (on `this`).\n\n```js\nfunction User(name) {\n  this.name = name                    \u002F\u002F instance data\n}\nUser.prototype.greet = function () {   \u002F\u002F shared method\n  return `Hi, ${this.name}`\n}\n```\n\nDefining methods inside the constructor (`this.greet = function(){}`) creates a\nnew function per instance — wasteful. Classes handle this correctly by placing\nmethods on the prototype automatically.\n",{"id":3732,"difficulty":84,"q":3733,"a":3734},"new-with-bind","What happens when you use new on a bound function?","`new` **overrides** a bound `this` — the instance wins. Bound *arguments* are\nstill applied.\n\n```js\nfunction Point(x, y) { this.x = x; this.y = y }\nconst Bound = Point.bind({ ignored: true }, 10)  \u002F\u002F pre-bind x = 10\nconst p = new Bound(20)\np.x  \u002F\u002F 10 (bound arg kept)\np.y  \u002F\u002F 20\n\u002F\u002F the bound `this` ({ ignored: true }) is ignored — p is a fresh Point\n```\n\nThis reflects precedence: `new` beats explicit binding. It's the one case where\n`bind`'s \"permanent\" `this` doesn't hold.\n",{"id":3736,"difficulty":63,"q":3737,"a":3738},"class-not-hoisted","Can you use a constructor before it is defined?","**Function** constructors are hoisted (usable before their line); **class**\nconstructors are hoisted but in the temporal dead zone, so they're **not** usable\nearly.\n\n```js\nnew Fn()              \u002F\u002F works — function declaration hoisted\nfunction Fn() {}\n\nnew Cls()             \u002F\u002F ReferenceError — TDZ\nclass Cls {}\n```\n\nSo switching from a constructor function to a class can break code that\ninstantiated it above its declaration. Always declare classes before use.\n",{"id":3740,"difficulty":84,"q":3741,"a":3742},"abstract-base","How do you make an abstract base constructor that can't be instantiated?","Check `new.target` against the base and throw, so only subclasses can be\ncreated.\n\n```js\nclass Shape {\n  constructor() {\n    if (new.target === Shape) throw new Error('Shape is abstract')\n  }\n  area() { throw new Error('not implemented') }\n}\nclass Circle extends Shape { area() { return 1 } }\nnew Shape()   \u002F\u002F throws\nnew Circle()  \u002F\u002F\n```\n\nJavaScript has no built-in `abstract` keyword, so `new.target` (plus throwing\nfrom unimplemented methods) is the idiom for abstract base classes.\n",{"id":3744,"difficulty":84,"q":3745,"a":3746},"reflect-construct","What is Reflect.construct?","The functional form of `new` — it invokes a constructor and optionally lets you\nspecify a different prototype (`newTarget`), useful in metaprogramming and for\nsubclassing built-ins.\n\n```js\nconst obj = Reflect.construct(Array, [1, 2, 3])   \u002F\u002F like new Array(1,2,3)\n\u002F\u002F third arg sets new.target \u002F the prototype to use:\nReflect.construct(Base, args, Derived)\n```\n\nIt's how you invoke a constructor dynamically (with an args array) and control\nthe resulting prototype — the building block frameworks use for advanced\ninstantiation.\n",{"id":3748,"difficulty":63,"q":3749,"a":3750},"chaining-constructors","How do constructor functions call a parent constructor?","Call the parent with `Parent.call(this, args)` so the parent initializes the\nchild's instance fields.\n\n```js\nfunction Animal(name) { this.name = name }\nfunction Dog(name, breed) {\n  Animal.call(this, name)   \u002F\u002F parent sets this.name\n  this.breed = breed\n}\n```\n\nThis is the pre-class way to \"chain\" constructors. With classes, `super(name)`\ndoes the same thing, and is required before using `this` in a subclass.\n",{"id":3752,"difficulty":71,"q":3753,"a":3754},"typeof-constructor","What does typeof return for a constructor or class?","`'function'` — both constructor functions and classes are functions under the\nhood.\n\n```js\nfunction Fn() {}\nclass Cls {}\ntypeof Fn    \u002F\u002F 'function'\ntypeof Cls   \u002F\u002F 'function'\n```\n\nClasses are special functions (strict mode, non-enumerable methods, must be\ncalled with `new`), but `typeof` doesn't distinguish them. To tell a class from\na regular function, you'd inspect the source or try calling without `new`.\n",{"id":3756,"difficulty":63,"q":3757,"a":3758},"pure-constructor","Should constructors have side effects?","Keep constructors **focused on initialization**. Heavy work — network calls,\nDOM access, throwing on async failures — makes objects hard to create, test, and\nreason about.\n\n```js\n\u002F\u002F side-effectful constructor\nclass User { constructor(id) { this.data = fetch(`\u002Fu\u002F${id}`) } }\n\n\u002F\u002F construct simply, do work in a method\u002Fstatic factory\nclass User {\n  constructor(data) { this.data = data }\n  static async load(id) { return new User(await (await fetch(`\u002Fu\u002F${id}`)).json()) }\n}\n```\n\nA common pattern is a **static async factory** (`User.load`) that does the I\u002FO\nand then constructs a plain instance — constructors can't be async.\n",{"id":3760,"difficulty":71,"q":3761,"a":3762},"new-object-vs-literal","Why prefer object literals over new Object?","`{}` is shorter, clearer, and slightly faster than `new Object()`, with no\ndownside. The same goes for `[]` over `new Array()` and `\u002Fregex\u002F` over\n`new RegExp()` for static patterns.\n\n```js\nconst a = {}            \u002F\u002F idiomatic\nconst b = new Object()  \u002F\u002F verbose, no benefit\n```\n\nUse `new` for types that genuinely need a constructor (`Date`, `Map`, `Set`,\n`Promise`, custom classes), and literals for the primitives-with-literals\n(objects, arrays, regexes).\n",{"id":3764,"difficulty":63,"q":3765,"a":3766},"constructor-returning-this","How do you enable method chaining from a constructor's methods?","Have each method `return this`, so calls can be chained on the instance.\n\n```js\nclass QueryBuilder {\n  constructor() { this.parts = [] }\n  where(c) { this.parts.push(c); return this }\n  order(o) { this.parts.push(o); return this }\n  build() { return this.parts.join(' ') }\n}\nnew QueryBuilder().where('a=1').order('b').build()\n```\n\nReturning `this` (the instance) from methods is the builder\u002Ffluent pattern. It\nworks because methods are called on the instance, so `this` is consistent across\nthe chain.\n",{"id":3768,"difficulty":84,"q":3769,"a":3770},"private-with-closures","How do you make private data with a constructor function?","Use closures: declare variables inside the constructor and expose only methods\nthat close over them — the variables aren't accessible as properties.\n\n```js\nfunction Counter() {\n  let count = 0                          \u002F\u002F private\n  this.increment = () => ++count\n  this.value = () => count\n}\nconst c = new Counter()\nc.increment()\nc.value()   \u002F\u002F 1\nc.count     \u002F\u002F undefined — truly private\n```\n\nThe trade-off: these methods are per-instance (closures), not shared on the\nprototype. Modern classes offer `#private` fields for shared-method privacy\nwithout closures.\n",{"description":61},"JavaScript constructor interview questions — what the new operator does, constructor functions, returning values, new.target, and common new-related bugs.","javascript\u002Fobjects\u002Fnew-constructors","The new Operator & Constructors","Objects & Prototypes","objects","5aotjqlkjQas6w28TNEYJdSAiTtsD8hnRDnlHSFl6ys",{"id":3779,"title":3780,"body":3781,"description":61,"difficulty":63,"extension":64,"framework":11,"frameworkSlug":9,"meta":3785,"navigation":66,"order":12,"path":3786,"questions":3787,"related":207,"seo":3907,"seoDescription":3908,"stem":3909,"subtopic":3910,"topic":3775,"topicSlug":3776,"updated":214,"__hash__":3911},"qa\u002Fjavascript\u002Fobjects\u002Fobjects-properties.md","Objects Properties",{"type":58,"value":3782,"toc":3783},[],{"title":61,"searchDepth":22,"depth":22,"links":3784},[],{},"\u002Fjavascript\u002Fobjects\u002Fobjects-properties",[3788,3792,3796,3800,3804,3808,3812,3816,3820,3824,3828,3832,3836,3840,3844,3848,3852,3856,3860,3864,3868,3872,3876,3880,3884,3888,3891,3895,3899,3903],{"id":3789,"difficulty":71,"q":3790,"a":3791},"create-object","What are the ways to create an object in JavaScript?","Several, each with different use cases:\n\n```js\nconst a = {}                       \u002F\u002F object literal (most common)\nconst b = new Object()             \u002F\u002F constructor (rarely used)\nconst c = Object.create(proto)     \u002F\u002F with an explicit prototype\nfunction Point(x) { this.x = x }   \u002F\u002F constructor function\nconst d = new Point(1)\nclass P {}                         \u002F\u002F class\nconst e = new P()\n```\n\nThe **object literal** `{}` is by far the most common. `Object.create(proto)`\nis the only one that lets you set the prototype directly (or create a\nprototype-less object with `Object.create(null)`). Constructor functions and\nclasses are for producing many similar objects.\n",{"id":3793,"difficulty":71,"q":3794,"a":3795},"access-properties","What is the difference between dot and bracket notation?","**Dot notation** (`obj.name`) is concise but only works for fixed, valid\nidentifier keys. **Bracket notation** (`obj['name']`) accepts any string or a\ncomputed expression — required for dynamic keys, keys with spaces\u002Fspecial\ncharacters, or numeric-like keys.\n\n```js\nobj.firstName          \u002F\u002F static key\nobj['first-name']      \u002F\u002F key with a hyphen — dot won't work\nconst key = 'age'\nobj[key]               \u002F\u002F dynamic key from a variable\n```\n\nUse dot notation by default; reach for brackets when the key is dynamic or not\na valid identifier.\n",{"id":3797,"difficulty":71,"q":3798,"a":3799},"property-shorthand","What are shorthand properties and computed property names?","**Shorthand** lets you omit the value when a variable has the same name as the\nkey. **Computed names** let you use an expression as a key inside a literal.\n\n```js\nconst name = 'Ada', age = 36\nconst user = { name, age }              \u002F\u002F { name: 'Ada', age: 36 }\n\nconst field = 'email'\nconst obj = { [field]: 'a@b.com', [`is${field}`]: true }\n\u002F\u002F { email: 'a@b.com', isemail: true }\n\nconst methods = { greet() { return 'hi' } } \u002F\u002F method shorthand\n```\n\nThese ES6 features make object construction terser and enable dynamic keys\nwithout a separate assignment.\n",{"id":3801,"difficulty":84,"q":3802,"a":3803},"property-descriptor","What is a property descriptor?","Every property has a **descriptor** describing its attributes. Data properties\nhave `value`, `writable`, `enumerable`, and `configurable`; accessor properties\nhave `get`, `set`, `enumerable`, `configurable`.\n\n```js\nconst obj = {}\nObject.defineProperty(obj, 'id', {\n  value: 1,\n  writable: false,     \u002F\u002F can't reassign\n  enumerable: false,   \u002F\u002F hidden from for...in \u002F Object.keys\n  configurable: false, \u002F\u002F can't delete or redefine\n})\nObject.getOwnPropertyDescriptor(obj, 'id')\n```\n\nProperties created normally default all flags to `true`; `defineProperty`\ndefaults them to `false`. Descriptors let you create read-only or\nnon-enumerable properties — used heavily by the language internals.\n",{"id":3805,"difficulty":63,"q":3806,"a":3807},"getters-setters","What are getters and setters?","Accessor properties that run a function on read (`get`) or write (`set`),\nletting a property be computed or validated while still being accessed like a\nnormal property.\n\n```js\nconst temp = {\n  celsius: 20,\n  get fahrenheit() { return this.celsius * 1.8 + 32 },\n  set fahrenheit(f) { this.celsius = (f - 32) \u002F 1.8 },\n}\ntemp.fahrenheit      \u002F\u002F 68 (computed)\ntemp.fahrenheit = 212\ntemp.celsius         \u002F\u002F 100\n```\n\nThey're useful for derived values, validation, and encapsulation. Define them\nwith `get`\u002F`set` syntax in a literal\u002Fclass, or via `Object.defineProperty`.\n",{"id":3809,"difficulty":71,"q":3810,"a":3811},"object-keys-values-entries","What do Object.keys, Object.values and Object.entries return?","They return arrays of an object's **own enumerable** string-keyed properties:\n\n```js\nconst o = { a: 1, b: 2 }\nObject.keys(o)    \u002F\u002F ['a', 'b']\nObject.values(o)  \u002F\u002F [1, 2]\nObject.entries(o) \u002F\u002F [['a', 1], ['b', 2]]\n\nfor (const [k, v] of Object.entries(o)) console.log(k, v)\n```\n\nThey ignore inherited and non-enumerable properties (and symbol keys). They're\nthe standard way to iterate objects, and `Object.fromEntries` reverses\n`entries` back into an object.\n",{"id":3813,"difficulty":63,"q":3814,"a":3815},"object-assign","What does Object.assign do?","`Object.assign(target, ...sources)` copies **own enumerable** properties from\nthe sources onto the target (a **shallow** copy) and returns the target.\n\n```js\nconst merged = Object.assign({}, defaults, overrides) \u002F\u002F merge into a new object\nconst clone = Object.assign({}, original)             \u002F\u002F shallow clone\n```\n\nIt only copies one level deep — nested objects are shared by reference. The\nspread operator `{ ...a, ...b }` does the same shallow merge more concisely and\nis usually preferred. `Object.assign` also triggers setters on the target.\n",{"id":3817,"difficulty":71,"q":3818,"a":3819},"spread-objects","How does the object spread operator work?","`{ ...obj }` copies an object's own enumerable properties into a new object — a\nconcise shallow copy\u002Fmerge. Later spreads override earlier keys.\n\n```js\nconst updated = { ...user, name: 'Grace' } \u002F\u002F copy + override one field\nconst merged = { ...defaults, ...options }   \u002F\u002F options win on conflicts\n```\n\nLike `Object.assign`, it's **shallow** — nested objects are shared. It's the\nidiomatic way to do immutable updates (especially in React). Spread copies\nvalues, not getters (it evaluates them).\n",{"id":3821,"difficulty":63,"q":3822,"a":3823},"delete-property","How do you remove a property from an object?","The `delete` operator removes a property entirely (so `'key' in obj` becomes\nfalse), returning `true` on success.\n\n```js\nconst obj = { a: 1, b: 2 }\ndelete obj.a\n'a' in obj  \u002F\u002F false\n```\n\nCaveats: `delete` only removes **own** properties (not inherited ones), can't\ndelete `configurable: false` properties, and can deoptimize objects in hot\npaths. For immutable removal, use destructuring: `const { a, ...rest } = obj`.\nSetting to `undefined` keeps the key; `delete` removes it.\n",{"id":3825,"difficulty":63,"q":3826,"a":3827},"check-property-exists","How do you check if a property exists on an object?","Three common approaches, each subtly different:\n\n```js\n'key' in obj                       \u002F\u002F true for own AND inherited properties\nobj.hasOwnProperty('key')          \u002F\u002F own properties only\nObject.hasOwn(obj, 'key')          \u002F\u002F own only (modern, safer)\nobj.key !== undefined              \u002F\u002F fails if the value IS undefined\n```\n\nUse `in` when inherited properties count; use `Object.hasOwn` (ES2022) for own\nproperties — it's safer than `hasOwnProperty`, which can be shadowed or missing\non `Object.create(null)` objects. Checking `=== undefined` is unreliable.\n",{"id":3829,"difficulty":84,"q":3830,"a":3831},"enumerable","What does \"enumerable\" mean for a property?","Enumerable properties show up in `for...in` loops, `Object.keys`, and spread;\nnon-enumerable ones are hidden from them (but still accessible directly).\n\n```js\nconst obj = { visible: 1 }\nObject.defineProperty(obj, 'hidden', { value: 2, enumerable: false })\nObject.keys(obj)             \u002F\u002F ['visible']\nobj.hidden                   \u002F\u002F 2 (still readable)\nObject.getOwnPropertyNames(obj) \u002F\u002F ['visible', 'hidden'] — includes non-enumerable\n```\n\nBuilt-in methods (like array methods on the prototype) are non-enumerable, so\nthey don't appear when you iterate. `getOwnPropertyNames` lists all own\nproperties regardless of enumerability.\n",{"id":3833,"difficulty":63,"q":3834,"a":3835},"for-in","What does for...in iterate over, and what is its pitfall?","`for...in` iterates **enumerable string keys**, including **inherited** ones\nfrom the prototype chain — which is its main pitfall.\n\n```js\nfor (const key in obj) {\n  if (Object.hasOwn(obj, key)) {   \u002F\u002F guard against inherited keys\n    console.log(key, obj[key])\n  }\n}\n```\n\nAlways guard with `Object.hasOwn`\u002F`hasOwnProperty` unless you want inherited\nkeys. For arrays, prefer `for...of` (values) or a normal loop — `for...in`\niterates indices as strings and includes non-index enumerable properties.\n",{"id":3837,"difficulty":63,"q":3838,"a":3839},"object-freeze","What is the difference between Object.freeze, seal and preventExtensions?","Three levels of locking down an object:\n\n- **`preventExtensions`** — can't add new properties; existing ones stay\n  writable\u002Fdeletable.\n- **`seal`** — preventExtensions + can't delete or reconfigure properties; values\n  still writable.\n- **`freeze`** — seal + can't change values. Fully immutable (shallowly).\n\n```js\nconst obj = Object.freeze({ a: 1, nested: { b: 2 } })\nobj.a = 9         \u002F\u002F ignored (throws in strict mode)\nobj.nested.b = 9  \u002F\u002F still works — freeze is SHALLOW\n```\n\nAll three are shallow. Check with `Object.isFrozen`\u002F`isSealed`. For deep\nimmutability, recursively freeze.\n",{"id":3841,"difficulty":84,"q":3842,"a":3843},"shallow-vs-deep-clone","How do you deep clone an object?","Shallow copies (`{ ...obj }`, `Object.assign`) share nested references. For a\nfully independent copy, use **`structuredClone`** (modern, handles cycles,\nDates, Maps), or a library.\n\n```js\nconst deep = structuredClone(original)   \u002F\u002F best built-in option\n\nconst viaJson = JSON.parse(JSON.stringify(original)) \u002F\u002F loses functions,\n\u002F\u002F undefined, Symbols; breaks on Dates\u002FMaps\u002Fcycles\n```\n\n`structuredClone` is the standard now; the `JSON` trick works only for plain\nJSON-safe data and silently mangles everything else.\n",{"id":3845,"difficulty":63,"q":3846,"a":3847},"object-references","Are objects compared by value or reference?","By **reference**. Two distinct objects with identical contents are not equal;\nonly two references to the *same* object are.\n\n```js\n{ a: 1 } === { a: 1 }   \u002F\u002F false (different objects)\nconst x = { a: 1 }\nconst y = x\nx === y                 \u002F\u002F true (same reference)\ny.a = 2; x.a            \u002F\u002F 2 — they share the object\n```\n\nAssigning an object copies the reference, not the object. This underlies\nshallow-copy bugs and why you need `structuredClone` for true independence.\n",{"id":3849,"difficulty":71,"q":3850,"a":3851},"optional-chaining-objects","How does optional chaining help with nested objects?","`?.` short-circuits to `undefined` if a reference is `null`\u002F`undefined`, instead\nof throwing — safe access into deep structures.\n\n```js\nuser?.address?.city           \u002F\u002F undefined if user or address is missing\nuser?.getName?.()             \u002F\u002F call only if it exists\ndata?.items?.[0]              \u002F\u002F safe index access\nconst city = user?.address?.city ?? 'unknown'\n```\n\nIt stops evaluating at the first nullish link. Pair it with `??` for defaults.\nDon't overuse it to mask data that *should* exist — it can hide bugs.\n",{"id":3853,"difficulty":63,"q":3854,"a":3855},"this-in-objects","What does this refer to in an object method?","In a regular-function method called as `obj.method()`, `this` is the object the\nmethod was called on. Extract the method, and `this` is lost.\n\n```js\nconst counter = {\n  count: 0,\n  inc() { this.count++ },\n}\ncounter.inc()              \u002F\u002F this === counter\nconst fn = counter.inc\nfn()                       \u002F\u002F this is undefined -> TypeError\n```\n\nUse method shorthand (a regular function) for methods that need `this`; avoid\narrow methods (their `this` is the outer scope, not the object).\n",{"id":3857,"difficulty":84,"q":3858,"a":3859},"object-create-null","What is Object.create(null) used for?","It creates an object with **no prototype** — a \"pure dictionary\" with no\ninherited properties or methods (`toString`, `hasOwnProperty`, etc.).\n\n```js\nconst dict = Object.create(null)\ndict.key = 'value'\ndict.toString          \u002F\u002F undefined — no Object.prototype\n'toString' in dict     \u002F\u002F false\n```\n\nUseful as a safe map where user-controlled keys won't collide with inherited\nproperty names (e.g. a key literally named `\"hasOwnProperty\"`). The trade-off:\nobject methods aren't available, so use `Object.keys(dict)` etc. (A `Map` is\noften a cleaner choice.)\n",{"id":3861,"difficulty":63,"q":3862,"a":3863},"object-vs-map","When should you use a Map instead of an object?","Use a **`Map`** when keys are dynamic or non-string, when you need ordering and\neasy size, or when you frequently add\u002Fremove entries.\n\n| | Object | Map |\n| --- | --- | --- |\n| Keys | strings\u002Fsymbols | **any type** |\n| Order | mostly insertion (quirky for integer keys) | guaranteed insertion |\n| Size | `Object.keys(o).length` | `map.size` |\n| Iteration | needs `Object.entries` | directly iterable |\n| Prototype keys | risk of collisions | none |\n\nUse a plain **object** for fixed, known-shape records and when you need JSON\nserialization (Maps don't `JSON.stringify` directly).\n",{"id":3865,"difficulty":84,"q":3866,"a":3867},"getownpropertynames","How do you list all properties including non-enumerable and symbols?","`Object.keys` misses non-enumerable and symbol keys. Use the fuller reflection\nmethods:\n\n```js\nObject.getOwnPropertyNames(obj)    \u002F\u002F all string keys (incl. non-enumerable)\nObject.getOwnPropertySymbols(obj)  \u002F\u002F symbol keys\nReflect.ownKeys(obj)               \u002F\u002F EVERYTHING: strings + symbols\n```\n\n`Reflect.ownKeys` is the complete list of own keys. These are needed for deep\ncloning, serialization, and metaprogramming where you must see every property.\n",{"id":3869,"difficulty":84,"q":3870,"a":3871},"property-order","In what order are object keys iterated?","Modern engines follow a spec order: **integer-like keys first, in ascending\nnumeric order**, then **string keys in insertion order**, then **symbol keys in\ninsertion order**.\n\n```js\nconst obj = { b: 1, 2: 1, a: 1, 1: 1 }\nObject.keys(obj) \u002F\u002F ['1', '2', 'b', 'a'] — numbers sorted, then strings as added\n```\n\nSo integer-like keys are *not* in insertion order — a surprise if you rely on\norder. If you need strict insertion order for all keys, use a **`Map`**.\n",{"id":3873,"difficulty":71,"q":3874,"a":3875},"method-vs-property","What is the difference between a method and a property?","A **property** holds a value; a **method** is a property whose value is a\nfunction, so it can be called.\n\n```js\nconst obj = {\n  name: 'Ada',           \u002F\u002F property\n  greet() { return 'hi' }, \u002F\u002F method (function-valued property)\n}\nobj.name      \u002F\u002F 'Ada'\nobj.greet()  \u002F\u002F 'hi'\n```\n\nMethods are just properties that happen to be functions — `typeof obj.greet`\nis `'function'`. Defining a method with shorthand also makes it non-arrow, so\n`this` works correctly.\n",{"id":3877,"difficulty":63,"q":3878,"a":3879},"tostring-override","How do you control how an object converts to a string or number?","Override `toString`\u002F`valueOf`, or implement `Symbol.toPrimitive` for full\ncontrol over coercion.\n\n```js\nconst money = {\n  amount: 100,\n  [Symbol.toPrimitive](hint) {\n    return hint === 'string' ? `$${this.amount}` : this.amount\n  },\n  toString() { return `$${this.amount}` },\n}\n`${money}`   \u002F\u002F '$100'\nmoney + 1    \u002F\u002F 101\n```\n\nWithout these, objects coerce to `[object Object]` (string) via `toString`.\n`Symbol.toPrimitive` takes precedence and receives a hint (`'string'`,\n`'number'`, `'default'`).\n",{"id":3881,"difficulty":63,"q":3882,"a":3883},"json-stringify-object","How does JSON.stringify handle objects?","It serializes **own enumerable** properties, but silently drops `undefined`,\nfunctions, and symbols, converts `NaN`\u002F`Infinity` to `null`, and calls a\n`toJSON()` method if present.\n\n```js\nJSON.stringify({ a: 1, b: undefined, c: () => {}, d: Symbol() })\n\u002F\u002F '{\"a\":1}'  — b, c, d dropped\n\nJSON.stringify(obj, ['a', 'b'])        \u002F\u002F replacer array: only these keys\nJSON.stringify(obj, null, 2)           \u002F\u002F pretty-print with 2-space indent\n```\n\n`BigInt` and circular references **throw**. The optional replacer and space\narguments control filtering and formatting.\n",{"id":3885,"difficulty":63,"q":3886,"a":3887},"chaining-optional-assignment","What does the logical assignment operator ||= and ??= do with objects?","They assign only when the left side is falsy (`||=`) or nullish (`??=`) — handy\nfor defaulting object properties.\n\n```js\nconst config = { timeout: 0 }\nconfig.timeout ||= 1000   \u002F\u002F 1000 overwrites valid 0\nconfig.timeout ??= 1000   \u002F\u002F 0    only fills null\u002Fundefined\nconfig.retries ??= 3      \u002F\u002F adds retries: 3\n```\n\n`??=` is the safe choice when `0`\u002F`''`\u002F`false` are valid values. They're\nshorthand for `x = x ?? value` and short-circuit (the right side isn't\nevaluated if no assignment happens).\n",{"id":2870,"difficulty":63,"q":3889,"a":3890},"How do you compare two objects for equality?","`===` only checks reference identity, so you must compare contents yourself for\n\"same data\" equality.\n\n```js\nconst shallowEqual = (a, b) => {\n  const ak = Object.keys(a), bk = Object.keys(b)\n  return ak.length === bk.length && ak.every((k) => a[k] === b[k])\n}\n```\n\nFor nested structures you need a recursive **deep equality** (lodash `isEqual`).\nThe `JSON.stringify(a) === JSON.stringify(b)` trick works only for simple data\nand is sensitive to key order and `undefined`.\n",{"id":3892,"difficulty":84,"q":3893,"a":3894},"defineproperties","What is the difference between defining a property and assigning it?","Plain assignment (`obj.x = 1`) creates an enumerable, writable, configurable\ndata property — or **triggers an inherited setter** if one exists.\n`Object.defineProperty` creates the property with explicit (default `false`)\nflags and **bypasses** setters.\n\n```js\nobj.x = 1   \u002F\u002F enumerable: true, writable: true, configurable: true\nObject.defineProperty(obj, 'y', { value: 2 })\n\u002F\u002F enumerable: false, writable: false, configurable: false\n```\n\nUse assignment for normal data; use `defineProperty` for read-only, hidden, or\naccessor properties, or to define multiple at once with `defineProperties`.\n",{"id":3896,"difficulty":71,"q":3897,"a":3898},"nullish-vs-or-default","How do you set default values when destructuring an object?","Provide defaults in the destructuring pattern; they apply only when the value\nis `undefined` (not `null` or other falsy values).\n\n```js\nconst { timeout = 1000, retries = 3, mode = 'auto' } = options\nconst { a: alias = 5 } = obj            \u002F\u002F rename + default\nfunction f({ x = 0, y = 0 } = {}) {}     \u002F\u002F default for the whole object too\n```\n\nThe `= {}` default on the parameter prevents a crash when the argument is\nomitted entirely. Defaults trigger only on `undefined`, so an explicit `null`\noverrides them.\n",{"id":3900,"difficulty":63,"q":3901,"a":3902},"copy-with-rest","How do you copy an object while omitting some properties?","Use destructuring with a **rest** pattern — the named keys are excluded, the\nrest collected into a new object.\n\n```js\nconst { password, ...safe } = user   \u002F\u002F `safe` has everything except password\nconst { [dynamicKey]: _, ...rest } = obj \u002F\u002F omit a dynamic key\n```\n\nThis is the idiomatic immutable \"remove a property\" — it produces a new object\nwithout mutating the original (unlike `delete`). Great for stripping sensitive\nfields before sending data.\n",{"id":3904,"difficulty":63,"q":3905,"a":3906},"object-grouping","How do you transform or group object data?","Convert to entries, transform, and convert back with `Object.fromEntries`:\n\n```js\n\u002F\u002F double every value\nconst doubled = Object.fromEntries(\n  Object.entries(obj).map(([k, v]) => [k, v * 2])\n)\n\u002F\u002F filter keys\nconst filtered = Object.fromEntries(\n  Object.entries(obj).filter(([, v]) => v > 10)\n)\n```\n\n`Object.entries` + array methods + `Object.fromEntries` is the functional\npattern for mapping\u002Ffiltering objects (which have no native `map`\u002F`filter`).\n`Object.groupBy` (ES2024) groups an array into an object by a key function.\n",{"description":61},"JavaScript object interview questions — creating objects, property descriptors, getters and setters, Object methods, enumeration, freezing and copying.","javascript\u002Fobjects\u002Fobjects-properties","Objects & Properties","8e9eu-hN4JNeXrO12JjJ3sUR5YmuDgSldUUI50UInGc",{"id":3913,"title":3914,"body":3915,"description":61,"difficulty":84,"extension":64,"framework":11,"frameworkSlug":9,"meta":3919,"navigation":66,"order":31,"path":3920,"questions":3921,"related":207,"seo":4025,"seoDescription":4026,"stem":4027,"subtopic":3914,"topic":3775,"topicSlug":3776,"updated":214,"__hash__":4028},"qa\u002Fjavascript\u002Fobjects\u002Fprototypal-inheritance.md","Prototypal Inheritance",{"type":58,"value":3916,"toc":3917},[],{"title":61,"searchDepth":22,"depth":22,"links":3918},[],{},"\u002Fjavascript\u002Fobjects\u002Fprototypal-inheritance",[3922,3926,3930,3934,3938,3942,3946,3950,3954,3958,3962,3966,3970,3974,3978,3982,3986,3990,3994,3998,4002,4005,4009,4013,4017,4021],{"id":3923,"difficulty":63,"q":3924,"a":3925},"what-is-prototypal-inheritance","What is prototypal inheritance?","A model where objects inherit directly from **other objects** (their prototype),\nrather than from classes. A missing property is looked up on the prototype\nchain, so one object can reuse another's properties and methods.\n\n```js\nconst animal = { eats: true, walk() { return 'walking' } }\nconst rabbit = Object.create(animal)\nrabbit.jumps = true\nrabbit.walk()  \u002F\u002F 'walking' — inherited\nrabbit.eats    \u002F\u002F true — inherited\n```\n\nJavaScript's inheritance is fundamentally object-to-object **delegation**. Even\n`class` is sugar over this prototypal mechanism.\n",{"id":3927,"difficulty":63,"q":3928,"a":3929},"object-create-inheritance","How do you implement inheritance with Object.create?","`Object.create(proto)` makes a new object whose prototype is `proto`, giving you\ndirect prototypal inheritance with no constructors.\n\n```js\nconst base = {\n  init(name) { this.name = name; return this },\n  describe() { return `I am ${this.name}` },\n}\nconst child = Object.create(base)\nchild.shout = function () { return this.describe().toUpperCase() }\n\nconst c = Object.create(child).init('Ada')\nc.shout()  \u002F\u002F 'I AM ADA'\n```\n\nEach level delegates to the one above. This is the most direct expression of\nprototypal inheritance — no `new`, no `prototype` juggling.\n",{"id":3931,"difficulty":84,"q":3932,"a":3933},"constructor-inheritance","How do you set up inheritance between constructor functions?","Call the parent constructor for the instance fields, and link the prototypes so\nmethods are inherited.\n\n```js\nfunction Animal(name) { this.name = name }\nAnimal.prototype.eat = function () { return `${this.name} eats` }\n\nfunction Dog(name) {\n  Animal.call(this, name)               \u002F\u002F inherit instance properties\n}\nDog.prototype = Object.create(Animal.prototype) \u002F\u002F inherit methods\nDog.prototype.constructor = Dog                 \u002F\u002F restore constructor\nDog.prototype.bark = function () { return 'woof' }\n```\n\nThis is the pre-ES6 pattern: `Parent.call(this)` for fields,\n`Object.create(Parent.prototype)` for the method chain, and reset\n`constructor`. `class extends` does all this for you.\n",{"id":3935,"difficulty":63,"q":3936,"a":3937},"class-vs-prototypal","What is the difference between classical and prototypal inheritance?","- **Classical** (Java\u002FC++): classes are blueprints; objects are **instances**\n  that copy structure from the class hierarchy.\n- **Prototypal** (JavaScript): objects **delegate** to live prototype objects;\n  there's no copying, and the link is dynamic.\n\n```js\n\u002F\u002F prototypal: changing the prototype affects existing objects live\nconst proto = { greet() { return 'hi' } }\nconst obj = Object.create(proto)\nproto.greet = () => 'hello'\nobj.greet()  \u002F\u002F 'hello' — live delegation, not a copy\n```\n\nJavaScript's `class` *looks* classical but is prototypal underneath. The key\ndifference is delegation (live links) vs copying (static blueprints).\n",{"id":3939,"difficulty":84,"q":3940,"a":3941},"super-in-prototypal","How do you call a parent method from a child (without class)?","Reference the parent prototype's method and invoke it with the right `this` via\n`call`.\n\n```js\nDog.prototype.eat = function () {\n  const base = Animal.prototype.eat.call(this)  \u002F\u002F call parent, keep `this`\n  return base + ' noisily'\n}\n```\n\nWith `class`, `super.method()` does this cleanly. Without classes, you must\nexplicitly grab `Parent.prototype.method` and `call` it with the instance, or\nthe parent method would run with the wrong `this`.\n",{"id":3943,"difficulty":71,"q":3944,"a":3945},"override-method","How does method overriding work with prototypes?","Define a method with the same name lower in the chain (on the child); it shadows\nthe parent's version because lookup stops at the first match.\n\n```js\nconst animal = { speak() { return '...' } }\nconst dog = Object.create(animal)\ndog.speak = function () { return 'Woof' }  \u002F\u002F overrides\ndog.speak()                                 \u002F\u002F 'Woof'\nObject.getPrototypeOf(dog).speak()          \u002F\u002F '...' (parent still reachable)\n```\n\nThe override is just a closer own\u002Fprototype property. The parent method remains\naccessible via the prototype if you need to call it (the manual `super`).\n",{"id":3947,"difficulty":63,"q":3948,"a":3949},"factory-functions","What are factory functions and how do they relate to inheritance?","A factory function returns a new object without `new` or classes — often using\nclosures for state and composition (rather than prototype chains) for behavior.\n\n```js\nfunction createUser(name) {\n  return {\n    name,\n    greet() { return `Hi, ${name}` },\n  }\n}\nconst u = createUser('Ada')\n```\n\nFactories favor **composition over inheritance**: instead of inheriting from a\nprototype, you assemble objects from pieces. Trade-off: methods aren't shared on\na prototype (each object gets its own), costing some memory for many instances.\n",{"id":3951,"difficulty":63,"q":3952,"a":3953},"mixins","What are mixins?","A way to share behavior across unrelated objects\u002Fclasses by **copying methods**\nin, instead of inheriting — JavaScript's answer to the lack of multiple\ninheritance.\n\n```js\nconst serializable = { serialize() { return JSON.stringify(this) } }\nconst comparable = { equals(o) { return this.id === o.id } }\n\nclass Model {}\nObject.assign(Model.prototype, serializable, comparable)\n```\n\nMixins let a class gain capabilities from several sources. They're a flexible\nalternative to deep inheritance — compose the behaviors a type needs rather than\nforcing a single hierarchy.\n",{"id":3955,"difficulty":84,"q":3956,"a":3957},"diamond-problem","Does JavaScript have the diamond problem?","Not in the classic multiple-inheritance sense, because each object has a\n**single** prototype chain — there's no ambiguity over which parent a method\ncomes from. But **mixins** can reintroduce conflicts when two mixins define the\nsame method.\n\n```js\nconst a = { run() { return 'a' } }\nconst b = { run() { return 'b' } }\nObject.assign(target, a, b)\ntarget.run()  \u002F\u002F 'b' — last one wins, silently\n```\n\nWith `Object.assign`, the last source wins on key collisions (no error). So\nsingle-prototype inheritance avoids diamonds, but you must manage mixin method\nclashes yourself.\n",{"id":3959,"difficulty":63,"q":3960,"a":3961},"prototype-vs-instance-property","Should shared state go on the prototype?","No — only **methods** (and true constants) belong on the prototype. Mutable\nshared state on a prototype is accidentally shared by all instances.\n\n```js\nfunction Cart() {}\nCart.prototype.items = []        \u002F\u002F ALL carts share one array\nconst a = new Cart(), b = new Cart()\na.items.push('x')\nb.items                          \u002F\u002F ['x'] — leaked!\n\nfunction Cart2() { this.items = [] }  \u002F\u002F per-instance state in the constructor\n```\n\nPut per-instance data on `this` in the constructor; put shared behavior on the\nprototype. (This mirrors the Java \"mutable static field\" trap.)\n",{"id":3963,"difficulty":84,"q":3964,"a":3965},"inherit-static","Are static-like properties inherited?","Constructor functions have their **own** prototype chain\n(`Child.__proto__ === Parent` when using `class extends`), so \"static\"\nproperties on the parent constructor are inherited by the child constructor.\n\n```js\nclass Parent { static create() { return new this() } }\nclass Child extends Parent {}\nChild.create()   \u002F\u002F works — static method inherited; `this` is Child\n```\n\n`extends` links both chains: instance methods via `Child.prototype ->\nParent.prototype`, and statics via `Child -> Parent`. With plain constructor\nfunctions you'd wire statics up manually.\n",{"id":3967,"difficulty":84,"q":3968,"a":3969},"object-create-second-arg","What is the second argument to Object.create?","A **property descriptors** object — it lets you define own properties (with\nwritable\u002Fenumerable\u002Fconfigurable flags) at the same time as setting the\nprototype.\n\n```js\nconst obj = Object.create(proto, {\n  id: { value: 1, enumerable: true },\n  secret: { value: 42, enumerable: false },\n})\n```\n\nIt's the same descriptor format as `Object.defineProperties`. Rarely needed, but\nit's how you create an object with both a chosen prototype and precisely\nconfigured own properties in one call.\n",{"id":3971,"difficulty":84,"q":3972,"a":3973},"parasitic-inheritance","What is parasitic \u002F functional inheritance?","An older pattern where a factory creates a base object, then **augments** it with\nextra properties\u002Fmethods before returning it — inheritance without prototypes.\n\n```js\nfunction createAnimal(name) {\n  const obj = { name }\n  obj.eat = () => `${name} eats`\n  return obj\n}\nfunction createDog(name) {\n  const dog = createAnimal(name)   \u002F\u002F \"inherit\" by starting from a base\n  dog.bark = () => 'woof'          \u002F\u002F augment\n  return dog\n}\n```\n\nIt uses composition\u002Fclosures instead of the prototype chain. Methods aren't\nshared (memory cost), but it's simple and avoids `this`\u002F`new` pitfalls.\n",{"id":3975,"difficulty":63,"q":3976,"a":3977},"hasownproperty-inheritance","Why can iterating an inheriting object surprise you?","`for...in` walks inherited enumerable properties too, so an object that inherits\nfrom another can expose more keys than you expect.\n\n```js\nconst proto = { shared: 1 }\nconst obj = Object.create(proto)\nobj.own = 2\nfor (const k in obj) console.log(k)   \u002F\u002F 'own' AND 'shared'\n```\n\nGuard with `Object.hasOwn(obj, k)`, or iterate `Object.keys(obj)` (own only).\nThis is why adding enumerable properties to built-in prototypes is dangerous —\nit pollutes every `for...in`.\n",{"id":3979,"difficulty":84,"q":3980,"a":3981},"super-property-vs-method","How does inheritance interact with getters and setters?","Inherited accessors run with the instance as `this`, so a child can override a\ngetter\u002Fsetter while the parent's still computes against the child's data.\n\n```js\nconst base = {\n  get label() { return `[${this.name}]` },\n}\nconst item = Object.create(base)\nitem.name = 'box'\nitem.label   \u002F\u002F '[box]' — inherited getter, `this` is item\n```\n\nOverriding an inherited setter and writing to the property creates an own data\nproperty unless the child also defines an accessor — a subtle source of bugs\nwhen mixing data and accessor properties across a chain.\n",{"id":3983,"difficulty":63,"q":3984,"a":3985},"composition-over-inheritance-js","Why is composition often preferred over inheritance in JavaScript?","Deep inheritance chains are rigid: a change in a base ripples to all\ndescendants, and an object is locked into one hierarchy. **Composition** builds\nobjects from small, swappable behaviors, which is more flexible.\n\n```js\nconst withTimestamp = (o) => ({ ...o, createdAt: Date.now() })\nconst withId = (o) => ({ ...o, id: crypto.randomUUID() })\nconst record = withId(withTimestamp({ name: 'Ada' }))\n```\n\nCompose capabilities (functions, mixins, delegation) instead of inheriting them.\nThis avoids the fragile-base-class problem and the \"gorilla holding the banana\nand the entire jungle\" inheritance trap.\n",{"id":3987,"difficulty":63,"q":3988,"a":3989},"instanceof-inheritance","How do you check an object's type through an inheritance chain?","`instanceof` returns true for any constructor whose `prototype` is in the chain,\nso it sees inherited types.\n\n```js\nclass Shape {}\nclass Circle extends Shape {}\nconst c = new Circle()\nc instanceof Circle   \u002F\u002F true\nc instanceof Shape    \u002F\u002F true (ancestor)\n```\n\nFor prototypal (non-class) inheritance, use\n`proto.isPrototypeOf(obj)` to ask \"is this object in obj's chain?\" — the\ndelegation-style equivalent of `instanceof`.\n",{"id":3991,"difficulty":63,"q":3992,"a":3993},"isprototypeof","What does isPrototypeOf do?","`proto.isPrototypeOf(obj)` returns true if `proto` appears anywhere in `obj`'s\nprototype chain — the object-oriented complement to `instanceof` (which works\nwith constructors).\n\n```js\nconst animal = {}\nconst dog = Object.create(animal)\nanimal.isPrototypeOf(dog)            \u002F\u002F true\nObject.prototype.isPrototypeOf(dog)  \u002F\u002F true\n```\n\nIt's the natural type check for prototypal inheritance built with\n`Object.create`, where there's no constructor to use with `instanceof`.\n",{"id":3995,"difficulty":63,"q":3996,"a":3997},"shared-method-this","How does this behave in an inherited method?","An inherited method is called on the instance, so `this` is the **instance**,\nnot the prototype where the method is defined.\n\n```js\nconst proto = { whoAmI() { return this.name } }\nconst a = Object.create(proto); a.name = 'A'\nconst b = Object.create(proto); b.name = 'B'\na.whoAmI()  \u002F\u002F 'A'\nb.whoAmI()  \u002F\u002F 'B' — same method, different `this`\n```\n\nThis is what makes shared prototype methods useful: one definition operates on\nwhichever instance invokes it. Lose the receiver (extract the method) and `this`\nbreaks, as always.\n",{"id":3999,"difficulty":63,"q":4000,"a":4001},"multiple-levels","Can you have multiple levels of prototypal inheritance?","Yes — chains can be arbitrarily deep, each level delegating to the next.\n\n```js\nconst a = { x: 1 }\nconst b = Object.create(a); b.y = 2\nconst c = Object.create(b); c.z = 3\nc.x  \u002F\u002F 1 (from a, two levels up)\nc.y  \u002F\u002F 2 (from b)\nc.z  \u002F\u002F 3 (own)\n```\n\nLookup walks `c -> b -> a -> Object.prototype -> null`. Deep chains work but get\nharder to reason about and slightly slower to traverse; flatter structures (or\ncomposition) are usually clearer.\n",{"id":3688,"difficulty":84,"q":4003,"a":4004},"What is new.target and how does it help with inheritance?","`new.target` is the constructor that was invoked with `new` (or `undefined` for\na normal call). It lets a base constructor know which subclass is being built and\nenforce `new`.\n\n```js\nfunction Base() {\n  if (!new.target) throw new Error('Use new')\n  console.log(new.target.name)   \u002F\u002F logs the actual subclass\n}\nclass Sub extends Base {}\nnew Sub()   \u002F\u002F logs 'Sub'\n```\n\nUseful for abstract base classes (throw if `new.target === Base`) and for\nfactory logic that depends on the concrete type being constructed.\n",{"id":4006,"difficulty":63,"q":4007,"a":4008},"prototype-chain-json","Does JSON.stringify include inherited properties?","No — `JSON.stringify` serializes **own enumerable** properties only, ignoring\nanything inherited from the prototype.\n\n```js\nconst proto = { inherited: 1 }\nconst obj = Object.create(proto)\nobj.own = 2\nJSON.stringify(obj)   \u002F\u002F '{\"own\":2}' — inherited is omitted\n```\n\nSo data on a prototype won't be serialized. If you need inherited values in\nJSON, copy them onto the object first (`{ ...proto, ...obj }`) or implement\n`toJSON`.\n",{"id":4010,"difficulty":63,"q":4011,"a":4012},"when-classes-vs-prototypes","Should you use classes or raw prototypes today?","For most code, **use `class`** — it's clearer, standard, and handles the\nprototype wiring (`extends`\u002F`super`\u002Fstatics) correctly. Reach for raw\nprototypes\u002F`Object.create` only for low-level work, OLOO-style delegation, or\nunderstanding internals.\n\n```js\n\u002F\u002F idiomatic modern inheritance\nclass Animal { constructor(n) { this.name = n } speak() {} }\nclass Dog extends Animal { speak() { return 'Woof' } }\n```\n\nClasses and prototypes are the same machinery; classes just give you a safer,\nmore readable interface. Knowing prototypes still matters for debugging and edge\ncases.\n",{"id":4014,"difficulty":63,"q":4015,"a":4016},"augmenting-instances","What is the cost of adding methods to instances vs the prototype?","Methods added to each **instance** are duplicated per object (more memory);\nmethods on the **prototype** are shared (one copy).\n\n```js\n\u002F\u002F a new function per instance\nfunction User(name) {\n  this.name = name\n  this.greet = function () { return this.name }\n}\n\u002F\u002F shared once\nUser.prototype.greet = function () { return this.name }\n```\n\nFor a handful of objects it doesn't matter; for thousands, prototype methods\nsave significant memory. Factory functions trade this away for closure-based\nprivacy — a deliberate choice.\n",{"id":4018,"difficulty":63,"q":4019,"a":4020},"delegation-events","How does delegation in prototypes relate to event delegation?","Both are \"delegation\" but different ideas. **Prototypal delegation** forwards\n*property lookups* up the prototype chain. **Event delegation** attaches one\nlistener to a parent that handles events from many children via bubbling.\n\n```js\n\u002F\u002F event delegation (unrelated to prototypes)\nlist.addEventListener('click', (e) => {\n  if (e.target.matches('li')) handle(e.target)\n})\n```\n\nThey share a name and a \"let something else handle it\" spirit, but operate in\ncompletely different parts of the language\u002FDOM — a common point of confusion.\n",{"id":4022,"difficulty":84,"q":4023,"a":4024},"clone-with-prototype","How do you clone an object while preserving its prototype?","Spread\u002F`Object.assign` copy own properties but give the clone a **plain object\nprototype**, losing the original's prototype. Preserve it explicitly:\n\n```js\nconst clone = Object.assign(\n  Object.create(Object.getPrototypeOf(original)),\n  original,\n)\n\u002F\u002F or structuredClone — but it does NOT preserve custom prototypes either\n```\n\n`{ ...obj }` and `structuredClone` both drop the custom prototype (the clone\nbecomes a plain object). To keep behavior, create the clone with\n`Object.create(getPrototypeOf(original))` then copy the own properties.\n",{"description":61},"JavaScript prototypal inheritance interview questions — Object.create, delegation, constructor inheritance, classical vs prototypal, and sharing behavior between objects.","javascript\u002Fobjects\u002Fprototypal-inheritance","GvqUS3PImrZ3Q2MJBGdT3949HLkhsnt0F70ivtrPQog",{"id":4030,"title":4031,"body":4032,"description":61,"difficulty":84,"extension":64,"framework":11,"frameworkSlug":9,"meta":4036,"navigation":66,"order":22,"path":4037,"questions":4038,"related":207,"seo":4154,"seoDescription":4155,"stem":4156,"subtopic":4157,"topic":3775,"topicSlug":3776,"updated":214,"__hash__":4158},"qa\u002Fjavascript\u002Fobjects\u002Fprototypes-chain.md","Prototypes Chain",{"type":58,"value":4033,"toc":4034},[],{"title":61,"searchDepth":22,"depth":22,"links":4035},[],{},"\u002Fjavascript\u002Fobjects\u002Fprototypes-chain",[4039,4043,4047,4051,4055,4059,4063,4067,4071,4074,4078,4082,4086,4090,4094,4098,4102,4106,4110,4114,4118,4122,4126,4130,4134,4138,4142,4146,4150],{"id":4040,"difficulty":63,"q":4041,"a":4042},"what-is-prototype","What is a prototype in JavaScript?","Every object has an internal link to another object called its **prototype**.\nWhen you access a property that the object doesn't have, JavaScript looks it up\non the prototype, then that object's prototype, and so on — the **prototype\nchain**. This is how objects inherit behavior in JavaScript.\n\n```js\nconst arr = [1, 2, 3]\narr.map(x => x)  \u002F\u002F `map` isn't on `arr`; it's found on Array.prototype\n```\n\nPrototypes are how methods are **shared** across many instances without copying\nthem onto each object — the foundation of JavaScript's object model.\n",{"id":4044,"difficulty":84,"q":4045,"a":4046},"proto-vs-prototype","What is the difference between __proto__ and prototype?","They're related but distinct:\n\n- **`prototype`** is a property of **constructor functions** (and classes). It's\n  the object that becomes the prototype of instances created with `new`.\n- **`__proto__`** (or `Object.getPrototypeOf`) is the actual **prototype link**\n  on every object — pointing to the object it inherits from.\n\n```js\nfunction Dog() {}\nconst d = new Dog()\nd.__proto__ === Dog.prototype          \u002F\u002F true\nObject.getPrototypeOf(d) === Dog.prototype \u002F\u002F true (preferred check)\n```\n\nSo `Constructor.prototype` is what *instances* get as their `__proto__`. Use\n`Object.getPrototypeOf`\u002F`setPrototypeOf` instead of the legacy `__proto__`.\n",{"id":4048,"difficulty":63,"q":4049,"a":4050},"prototype-chain-lookup","How does property lookup work along the prototype chain?","When you read `obj.prop`, the engine checks `obj` first; if not found, it\nfollows `obj`'s prototype, then that object's prototype, until it finds the\nproperty or reaches `null` (returning `undefined`).\n\n```js\nconst animal = { eats: true }\nconst dog = Object.create(animal)\ndog.barks = true\ndog.barks   \u002F\u002F true (own)\ndog.eats    \u002F\u002F true (inherited from animal)\ndog.flies   \u002F\u002F undefined (not found anywhere)\n```\n\nWriting a property, by contrast, always creates\u002Fupdates an **own** property on\nthe object itself — it doesn't modify the prototype (unless an inherited setter\nintercepts it).\n",{"id":4052,"difficulty":63,"q":4053,"a":4054},"end-of-chain","What is at the end of the prototype chain?","The chain ends at **`null`**. Most objects inherit from `Object.prototype`,\nwhose prototype is `null`.\n\n```js\nconst obj = {}\nObject.getPrototypeOf(obj) === Object.prototype       \u002F\u002F true\nObject.getPrototypeOf(Object.prototype) === null      \u002F\u002F true\n```\n\n`Object.prototype` provides `toString`, `hasOwnProperty`, `valueOf`, etc., which\nis why nearly every object has them. An object made with `Object.create(null)`\nhas **no** prototype, so its chain is empty.\n",{"id":4056,"difficulty":63,"q":4057,"a":4058},"methods-on-prototype","Why are methods defined on the prototype instead of each instance?","Putting methods on the prototype means **one shared copy** for all instances,\ninstead of a separate function per object — saving memory and allowing methods\nto be updated in one place.\n\n```js\nfunction User(name) { this.name = name }\nUser.prototype.greet = function () { return `Hi, ${this.name}` }\n\nconst a = new User('Ada'), b = new User('Bob')\na.greet === b.greet   \u002F\u002F true — shared method\n```\n\nEach instance holds only its own data (`name`); the behavior lives once on\n`User.prototype`. Classes do this automatically (methods go on the prototype).\n",{"id":4060,"difficulty":63,"q":4061,"a":4062},"hasownproperty","How do you tell own properties from inherited ones?","Use `hasOwnProperty` \u002F `Object.hasOwn`, which check **only own** properties,\nunlike `in` which also sees inherited ones.\n\n```js\nconst dog = Object.create({ eats: true })\ndog.barks = true\n'eats' in dog              \u002F\u002F true (inherited)\nObject.hasOwn(dog, 'eats') \u002F\u002F false (not own)\nObject.hasOwn(dog, 'barks')\u002F\u002F true\n```\n\n`Object.hasOwn` (ES2022) is the modern, robust form — it works even on\n`Object.create(null)` objects and can't be shadowed by an own property named\n`hasOwnProperty`.\n",{"id":4064,"difficulty":71,"q":4065,"a":4066},"getprototypeof","How do you get and set an object's prototype?","Use `Object.getPrototypeOf` to read and `Object.setPrototypeOf` (or\n`Object.create`) to set — prefer these over the legacy `__proto__`.\n\n```js\nconst proto = { greet() { return 'hi' } }\nconst obj = Object.create(proto)        \u002F\u002F create WITH a prototype\nObject.getPrototypeOf(obj) === proto     \u002F\u002F true\nObject.setPrototypeOf(obj, otherProto)   \u002F\u002F change it (slow — avoid in hot code)\n```\n\n`Object.setPrototypeOf` deoptimizes the object and is slow; set the prototype at\ncreation time with `Object.create` or a constructor\u002Fclass instead.\n",{"id":4068,"difficulty":63,"q":4069,"a":4070},"prototype-inheritance-vs-class","How do classes relate to prototypes?","`class` is **syntactic sugar** over prototypes. Class methods are put on the\nconstructor's `prototype`, and `extends` sets up the prototype chain — the same\nmechanism, nicer syntax.\n\n```js\nclass User {\n  constructor(name) { this.name = name }\n  greet() { return `Hi, ${this.name}` }   \u002F\u002F -> User.prototype.greet\n}\ntypeof User              \u002F\u002F 'function'\nUser.prototype.greet     \u002F\u002F the method lives here\n```\n\nUnder the hood there are no \"real\" classes — `class` desugars to constructor\nfunctions + prototype assignment, with some extras (strict mode, non-enumerable\nmethods, `new`-only invocation).\n",{"id":3028,"difficulty":63,"q":4072,"a":4073},"What is property shadowing in the prototype chain?","An **own** property with the same name as an inherited one **shadows** (hides)\nthe prototype's version — lookup stops at the own property.\n\n```js\nconst proto = { greet: () => 'from proto' }\nconst obj = Object.create(proto)\nobj.greet = () => 'from obj'\nobj.greet()  \u002F\u002F 'from obj' — shadows the prototype's greet\ndelete obj.greet\nobj.greet()  \u002F\u002F 'from proto' — inherited version reappears\n```\n\nAssigning to an inherited property creates an own one (shadowing); it doesn't\nchange the prototype. Deleting the own property reveals the inherited one again.\n",{"id":4075,"difficulty":63,"q":4076,"a":4077},"instanceof-prototype","How does instanceof use the prototype chain?","`obj instanceof Ctor` checks whether `Ctor.prototype` appears **anywhere** in\n`obj`'s prototype chain.\n\n```js\nclass Animal {}\nclass Dog extends Animal {}\nconst d = new Dog()\nd instanceof Dog     \u002F\u002F true\nd instanceof Animal  \u002F\u002F true (Animal.prototype is in the chain)\nd instanceof Object  \u002F\u002F true\n```\n\nSo it tests prototype-chain membership, not the exact constructor. It can break\nacross realms (iframes) and if you reassign `prototype`; `Symbol.hasInstance`\ncan customize its behavior.\n",{"id":4079,"difficulty":84,"q":4080,"a":4081},"constructor-property","What is the constructor property on the prototype?","Every function's `prototype` object has a `constructor` property pointing back\nto the function. Instances inherit it, so you can find the constructor that made\nan object.\n\n```js\nfunction User() {}\nUser.prototype.constructor === User   \u002F\u002F true\nconst u = new User()\nu.constructor === User                 \u002F\u002F true (inherited)\n```\n\nGotcha: if you **replace** `Prototype` entirely (`User.prototype = {...}`), you\nlose the `constructor` link unless you set it back. It's mostly informational\nand shouldn't be relied on for type checks.\n",{"id":4083,"difficulty":84,"q":4084,"a":4085},"extend-builtin","Can you add methods to built-in prototypes, and should you?","You technically can (`Array.prototype.last = function(){...}`), but you\n**shouldn't** — modifying built-in prototypes (monkey-patching) risks clashing\nwith future language features or other libraries, and breaks `for...in`.\n\n```js\n\u002F\u002F avoid — pollutes every array, may collide with a future Array.prototype\nArray.prototype.last = function () { return this[this.length - 1] }\n```\n\nPrefer standalone utility functions or subclasses. The one time it's acceptable\nis a carefully scoped **polyfill** that implements a standardized method on old\nengines.\n",{"id":4087,"difficulty":84,"q":4088,"a":4089},"prototype-pollution","What is prototype pollution?","A security vulnerability where untrusted input modifies `Object.prototype`,\naffecting **every** object in the program — often via unsafe deep-merge or\nproperty assignment using a `__proto__` key.\n\n```js\n\u002F\u002F attacker payload: { \"__proto__\": { \"isAdmin\": true } }\nmerge({}, JSON.parse(userInput))\n;({}).isAdmin   \u002F\u002F true — every object now \"has\" isAdmin\n```\n\nMitigate by rejecting `__proto__`\u002F`constructor`\u002F`prototype` keys, using\n`Object.create(null)` or `Map` for user data, and `Object.freeze(Object.\nprototype)`. It's a real-world exploit in many libraries.\n",{"id":4091,"difficulty":71,"q":4092,"a":4093},"array-prototype-methods","Where do array and string methods come from?","They live on the built-in prototypes — `Array.prototype`, `String.prototype`,\netc. — and are inherited by every array\u002Fstring via the prototype chain.\n\n```js\n[1, 2].map          === Array.prototype.map     \u002F\u002F true\n'hi'.toUpperCase    === String.prototype.toUpperCase \u002F\u002F true\n```\n\nThat's why all arrays share the same `map`\u002F`filter`. Primitives like strings are\ntemporarily **boxed** into wrapper objects so they can reach their prototype\nmethods, then discarded.\n",{"id":4095,"difficulty":84,"q":4096,"a":4097},"borrow-methods","How do you borrow methods from a prototype?","Use `call`\u002F`apply` to invoke a prototype method with a different `this` — handy\nfor array-like objects that lack array methods.\n\n```js\nfunction sum() {\n  return Array.prototype.reduce.call(arguments, (a, b) => a + b, 0)\n}\nArray.prototype.slice.call(document.querySelectorAll('div')) \u002F\u002F NodeList -> array\n```\n\nMethod borrowing leverages that prototype methods are just functions decoupled\nfrom their objects via `this`. Modern code often uses `Array.from`\u002Fspread\ninstead, but borrowing shows how the chain and `this` interact.\n",{"id":4099,"difficulty":63,"q":4100,"a":4101},"own-vs-inherited-enumeration","Do Object.keys and for...in include inherited properties?","- **`Object.keys`** — own enumerable properties only.\n- **`for...in`** — own **and inherited** enumerable properties.\n\n```js\nconst proto = { inherited: 1 }\nconst obj = Object.create(proto)\nobj.own = 2\nObject.keys(obj)            \u002F\u002F ['own']\nfor (const k in obj) console.log(k)  \u002F\u002F 'own', then 'inherited'\n```\n\nThis is why `for...in` needs a `hasOwn` guard. Built-in prototype methods are\nnon-enumerable, so they don't show up in `for...in` — only your own additions\nto prototypes would.\n",{"id":4103,"difficulty":63,"q":4104,"a":4105},"create-vs-new","What is the difference between Object.create and new?","- **`Object.create(proto)`** sets the new object's prototype to `proto` and runs\n  **no constructor**.\n- **`new Fn()`** creates an object whose prototype is `Fn.prototype`, then runs\n  `Fn` as a constructor (initializing the object).\n\n```js\nconst a = Object.create(protoObj)   \u002F\u002F prototype = protoObj, no init\nconst b = new Ctor(args)            \u002F\u002F prototype = Ctor.prototype, runs Ctor\n```\n\n`Object.create` is lower-level (just sets up the link); `new` is the full\nconstructor flow. `new Ctor()` is roughly `Object.create(Ctor.prototype)` plus\ncalling `Ctor` with the new object as `this`.\n",{"id":4107,"difficulty":84,"q":4108,"a":4109},"differential-inheritance","What is \"differential inheritance\" \u002F delegation?","JavaScript's prototype model is **delegation-based**: objects don't copy\nproperties from a \"class,\" they **delegate** missing property lookups to their\nprototype at runtime. Each object stores only what differs from its prototype.\n\n```js\nconst base = { type: 'shape', area() { return 0 } }\nconst circle = Object.create(base)\ncircle.r = 2\ncircle.area = function () { return Math.PI * this.r ** 2 } \u002F\u002F override only this\n```\n\nChanges to the prototype are immediately visible to all delegating objects (a\nlive link), unlike class-based copying. This is why the model is sometimes\ncalled \"objects linking to other objects\" (OLOO).\n",{"id":4111,"difficulty":63,"q":4112,"a":4113},"prototype-method-update","What happens if you change a prototype after instances exist?","Because the prototype link is **live**, existing instances immediately see\nchanges to their prototype.\n\n```js\nfunction User() {}\nconst u = new User()\nUser.prototype.greet = function () { return 'hi' }\nu.greet()   \u002F\u002F 'hi' — added after u was created, but visible\n```\n\nThis is a consequence of delegation: instances don't copy the prototype, they\nreference it. (Reassigning the whole `prototype` object, however, only affects\n*future* instances — existing ones keep their old prototype.)\n",{"id":4115,"difficulty":63,"q":4116,"a":4117},"typeof-vs-instanceof","When do you use typeof vs instanceof?","- **`typeof`** — for **primitives** and detecting functions (`'string'`,\n  `'number'`, `'function'`, …).\n- **`instanceof`** — for checking whether an object is built by a particular\n  constructor\u002Fclass (prototype-chain membership).\n\n```js\ntypeof 'hi'           \u002F\u002F 'string'\ntypeof []             \u002F\u002F 'object' (useless for arrays)\n[] instanceof Array   \u002F\u002F true\nnew Date instanceof Date \u002F\u002F true\n```\n\n`typeof null` is `'object'` and `typeof []` is `'object'`, so use\n`Array.isArray` for arrays and `instanceof`\u002Fduck-typing for object kinds.\n",{"id":4119,"difficulty":84,"q":4120,"a":4121},"function-prototype","Do arrow functions have a prototype property?","No. Arrow functions **lack a `prototype`** property and can't be used with\n`new`, because they're not designed to be constructors.\n\n```js\nconst arrow = () => {}\narrow.prototype          \u002F\u002F undefined\nnew arrow()              \u002F\u002F TypeError: arrow is not a constructor\n\nfunction regular() {}\nregular.prototype        \u002F\u002F {} — usable as a constructor\n```\n\nOnly regular functions (and classes) have a `prototype` object for building\ninstances. This is one of several reasons arrows are lightweight callbacks, not\ngeneral-purpose functions.\n",{"id":4123,"difficulty":84,"q":4124,"a":4125},"chain-performance","Does a long prototype chain affect performance?","Slightly — each missing-property lookup walks the chain until found or `null`,\nso very deep chains add overhead. In practice engines optimize this heavily\n(inline caches), so it rarely matters for normal depths.\n\n```js\n\u002F\u002F accessing a deeply inherited property walks more links\ndeep.someInheritedMethod()  \u002F\u002F traverses several prototypes\n```\n\nBigger wins come from not reassigning prototypes at runtime\n(`setPrototypeOf` deoptimizes) and keeping object \"shapes\" stable. Don't\nmicro-optimize chain depth; do avoid dynamic prototype mutation in hot paths.\n",{"id":4127,"difficulty":84,"q":4128,"a":4129},"mixin-prototype","How do you mix methods from multiple sources into a prototype?","Since JavaScript has single-prototype inheritance, you compose extra behavior by\n**copying methods** onto a prototype — a mixin.\n\n```js\nconst serializable = { toJSON() { return { ...this } } }\nconst loggable = { log() { console.log(this) } }\n\nclass Model {}\nObject.assign(Model.prototype, serializable, loggable)\nnew Model().log()\n```\n\n`Object.assign(Class.prototype, ...mixins)` adds shared methods without a\nsuperclass — the standard way to share behavior across unrelated classes.\n",{"id":4131,"difficulty":63,"q":4132,"a":4133},"null-prototype-pitfall","What breaks when an object has no prototype?","`Object.create(null)` objects lack `Object.prototype`, so the usual methods\n(`toString`, `hasOwnProperty`, `valueOf`) are missing.\n\n```js\nconst dict = Object.create(null)\ndict.toString()              \u002F\u002F TypeError: not a function\n`${dict}`                    \u002F\u002F throws — can't coerce to string\nObject.keys(dict)            \u002F\u002F static methods still work\ndict.hasOwnProperty          \u002F\u002F undefined -> use Object.hasOwn(dict, k)\n```\n\nUse the **static** `Object.*` methods instead of instance methods. The benefit\n(no inherited keys to collide with) is why they're used as safe maps — but a\n`Map` usually avoids these pitfalls entirely.\n",{"id":4135,"difficulty":84,"q":4136,"a":4137},"setprototypeof-vs-create","Why is Object.setPrototypeOf discouraged?","Changing an existing object's prototype forces engines to **deoptimize** it\n(its hidden class\u002Fshape changes), which is slow and can hurt every later access\nto that object.\n\n```js\n\u002F\u002F slow — mutates an existing object's prototype\nconst obj = {}\nObject.setPrototypeOf(obj, proto)\n\n\u002F\u002F fast — set the prototype at creation\nconst obj2 = Object.create(proto)\n```\n\nSet the prototype **once at creation** (`Object.create`, a class, or a\nconstructor) rather than mutating it later. MDN explicitly warns about\n`setPrototypeOf`'s performance impact.\n",{"id":4139,"difficulty":63,"q":4140,"a":4141},"prototype-vs-composition","Is prototypal inheritance better than composition?","Neither is universally better — they solve different problems. Prototypal\ninheritance shares behavior down an is-a chain; **composition** builds behavior\nby combining small, independent pieces (often favored for flexibility).\n\n```js\n\u002F\u002F composition: assemble capabilities\nconst canFly = (s) => ({ fly: () => `${s.name} flies` })\nconst bird = (name) => { const s = { name }; return { ...s, ...canFly(s) } }\n```\n\nDeep inheritance chains get rigid; composition (mixins, factory functions,\ndelegation) tends to scale better. The common guidance \"favor composition over\ninheritance\" applies in JS too.\n",{"id":4143,"difficulty":84,"q":4144,"a":4145},"getter-on-prototype","Can getters and setters live on a prototype?","Yes — accessor properties defined on a prototype are inherited and run with the\ninstance as `this`, so derived values work per instance.\n\n```js\nclass Circle {\n  constructor(r) { this.r = r }\n  get area() { return Math.PI * this.r ** 2 }  \u002F\u002F on Circle.prototype\n}\nnew Circle(2).area   \u002F\u002F 12.56... — `this` is the instance\n```\n\nClass getters\u002Fsetters live on the prototype (shared definition), but execute\nagainst each instance. You can also add them via\n`Object.defineProperty(proto, 'x', { get, set })`.\n",{"id":4147,"difficulty":84,"q":4148,"a":4149},"realm-instanceof","Why can instanceof fail across iframes or realms?","Each realm (iframe, worker, Node vm) has its **own** built-in constructors and\nprototypes. An array from another frame has a different `Array.prototype`, so\n`arr instanceof Array` is `false` in your realm.\n\n```js\nconst iframeArray = iframe.contentWindow.eval('[1, 2]')\niframeArray instanceof Array   \u002F\u002F false — different Array constructor\nArray.isArray(iframeArray)     \u002F\u002F true — realm-agnostic\n```\n\nPrefer realm-safe checks: `Array.isArray`, `Object.prototype.toString.call(x)`\n(`'[object Array]'`), or duck typing — not `instanceof` — for cross-realm code.\n",{"id":4151,"difficulty":84,"q":4152,"a":4153},"oloo","What is the OLOO pattern?","\"Objects Linking to Other Objects\" — a style (popularized by Kyle Simpson) that\nuses `Object.create` and delegation directly, without constructors, `new`, or\nclasses, embracing JavaScript's prototypal nature.\n\n```js\nconst Widget = {\n  init(w) { this.width = w; return this },\n  render() { return `width: ${this.width}` },\n}\nconst button = Object.create(Widget).init(100)\nbutton.render()  \u002F\u002F 'width: 100'\n```\n\nIt avoids the `new`\u002F`this`\u002F`prototype` ceremony and makes the delegation\nexplicit. It's a minority style — classes are more common — but it clarifies how\nprototypes actually work.\n",{"description":61},"JavaScript prototype interview questions — the prototype chain, __proto__ vs prototype, property lookup, inheritance, and how methods are shared.","javascript\u002Fobjects\u002Fprototypes-chain","Prototypes & the Prototype Chain","apN3WJNktEDjBw2n8sZQhdM5ksCiMFRiWPSCKdSPYa8",{"id":4160,"title":4161,"body":4162,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":4166,"navigation":66,"order":31,"path":4167,"questions":4168,"related":207,"seo":4193,"seoDescription":4194,"stem":4195,"subtopic":4196,"topic":4197,"topicSlug":371,"updated":214,"__hash__":4198},"qa\u002Fpython\u002Fconcurrency\u002Fasyncio.md","Asyncio",{"type":58,"value":4163,"toc":4164},[],{"title":61,"searchDepth":22,"depth":22,"links":4165},[],{},"\u002Fpython\u002Fconcurrency\u002Fasyncio",[4169,4173,4177,4181,4185,4189],{"id":4170,"difficulty":84,"q":4171,"a":4172},"what-is-asyncio","What is asyncio and the event loop?","**asyncio** is Python's framework for **single-threaded concurrency** using an\n**event loop**. The **event loop** is a scheduler that runs many **coroutines**\ncooperatively: when one coroutine **awaits** something (typically I\u002FO), it\n**yields control** back to the loop, which runs another ready coroutine while the\nfirst waits. No thread is blocked sitting idle.\n\n```python\nimport asyncio\n\nasync def main():\n    print(\"hello\")\n    await asyncio.sleep(1)    # yields to the loop instead of blocking\n    print(\"world\")\n\nasyncio.run(main())           # creates the loop, runs main, then closes it\n```\n\nCrucially this is **concurrency, not parallelism** — one thread, one core,\ninterleaving tasks at `await` points. Rule of thumb: asyncio shines when you\nhave **many tasks that spend most of their time waiting** on I\u002FO.\n",{"id":4174,"difficulty":63,"q":4175,"a":4176},"async-def-await","What do async def and await do?","**`async def`** defines a **coroutine function** — calling it doesn't run the\nbody, it returns a **coroutine object** that must be awaited or scheduled.\n**`await`** **suspends** the current coroutine until the awaited **awaitable**\n(another coroutine, a Task, or a Future) completes, handing control back to the\nevent loop in the meantime.\n\n```python\nimport asyncio\n\nasync def fetch():\n    await asyncio.sleep(1)    # suspension point — loop runs others here\n    return \"data\"\n\nasync def main():\n    coro = fetch()            # nothing has run yet\n    result = await coro       # now it runs; main suspends until it finishes\n    print(result)\n\nasyncio.run(main())\n```\n\nYou can only `await` **inside** an `async def`. Forgetting to await a coroutine\nis a common bug — it never runs and you get a \"coroutine was never awaited\"\nwarning. Think of `await` as \"pause me here and let others run until this is\nready.\"\n",{"id":4178,"difficulty":84,"q":4179,"a":4180},"coroutines-vs-threads","How do coroutines differ from threads?","**Threads** use **preemptive** multitasking — the OS can switch threads at\n**any** point, so shared state needs locks and context switches are relatively\nexpensive. **Coroutines** use **cooperative** multitasking on **one thread** —\nswitches happen **only at explicit `await` points**, so the code between awaits\nis effectively atomic and switching is cheap.\n\n```python\nimport asyncio\n\nasync def task(name):\n    print(f\"{name} start\")\n    await asyncio.sleep(1)        # the ONLY place this can yield\n    print(f\"{name} done\")\n\nasync def main():\n    await asyncio.gather(task(\"a\"), task(\"b\"))   # thousands are feasible\n\nasyncio.run(main())\n```\n\nBecause there's no OS thread per task, you can run **tens of thousands** of\ncoroutines cheaply, and most data races disappear. The catch: a coroutine that\nnever awaits **monopolizes** the loop. Threads tolerate blocking code;\ncoroutines do not.\n",{"id":4182,"difficulty":63,"q":4183,"a":4184},"asyncio-gather","How do you run coroutines concurrently with asyncio.gather?","Awaiting coroutines one by one runs them **sequentially**. To run them\n**concurrently**, schedule them together with **`asyncio.gather`** (or wrap each\nin a **Task**), which lets the loop interleave their `await` points.\n\n```python\nimport asyncio\n\nasync def fetch(n):\n    await asyncio.sleep(1)\n    return n * 2\n\nasync def main():\n    # all three overlap -> ~1 second total, not 3\n    results = await asyncio.gather(fetch(1), fetch(2), fetch(3))\n    print(results)        # [2, 4, 6] — order matches the arguments\n\nasyncio.run(main())\n```\n\n`gather` returns results in argument order and, by default, propagates the first\nexception. `asyncio.create_task(coro)` schedules a coroutine to start running\nimmediately so it overlaps with later code. The key idea: concurrency comes from\n**scheduling tasks together**, not from awaiting them in turn.\n",{"id":4186,"difficulty":84,"q":4187,"a":4188},"dont-block-the-loop","What is the \"don't block the event loop\" rule?","Because asyncio runs on **one thread**, any code that **doesn't await** —\nheavy CPU work or **blocking synchronous I\u002FO** like `time.sleep`,\n`requests.get`, or blocking DB drivers — **freezes the entire loop**. Every other\ncoroutine stalls until that call returns.\n\n```python\nimport asyncio, time\n\nasync def bad():\n    time.sleep(5)              # BLOCKS the whole loop for 5s\n\nasync def good():\n    await asyncio.sleep(5)     # yields; other tasks keep running\n\n# offload unavoidable blocking\u002FCPU work to a thread or process pool:\nasync def offloaded():\n    loop = asyncio.get_running_loop()\n    await loop.run_in_executor(None, time.sleep, 5)   # runs in a thread\n```\n\nFixes: use **async-native libraries** (`aiohttp`, `asyncpg`), and push\nCPU-bound or unavoidably-blocking calls into `run_in_executor` (a thread pool, or\na process pool for CPU work). Rule of thumb: inside `async` code, never call\nsomething that blocks without awaiting it.\n",{"id":4190,"difficulty":63,"q":4191,"a":4192},"when-async-helps","When does asyncio actually help?","asyncio wins for **high-concurrency I\u002FO-bound** workloads — thousands of\nnetwork calls, web requests, websocket connections, or database queries that\nspend their time **waiting**. While one request waits, the loop services others,\nso a single thread handles huge concurrency cheaply.\n\n```python\nimport asyncio\n\nasync def call_api(i):\n    await asyncio.sleep(0.5)        # stand-in for a network round trip\n    return i\n\nasync def main():\n    # 1000 \"requests\" overlap on one thread in ~0.5s of wall time\n    results = await asyncio.gather(*(call_api(i) for i in range(1000)))\n    print(len(results))             # 1000\n\nasyncio.run(main())\n```\n\nIt does **not** help **CPU-bound** work — that needs multiprocessing for real\nparallelism. And for a handful of blocking calls, plain threads are often\nsimpler. Reach for asyncio when concurrency is high and the bottleneck is\nwaiting on I\u002FO.\n",{"description":61},"Python interview questions on asyncio and async\u002Fawait: the event loop, coroutines vs threads, asyncio.gather, the don't-block-the-loop rule, and when async helps.","python\u002Fconcurrency\u002Fasyncio","asyncio & async\u002Fawait","Concurrency & Parallelism","Nmpm5dZjqwdFh49NpQFVIUo_4pc2dAboUlrFVlULydE",{"id":4200,"title":4201,"body":4202,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4206,"navigation":66,"order":40,"path":4207,"questions":4208,"related":207,"seo":4233,"seoDescription":4234,"stem":4235,"subtopic":4236,"topic":4197,"topicSlug":371,"updated":214,"__hash__":4237},"qa\u002Fpython\u002Fconcurrency\u002Fconcurrent-futures.md","Concurrent Futures",{"type":58,"value":4203,"toc":4204},[],{"title":61,"searchDepth":22,"depth":22,"links":4205},[],{},"\u002Fpython\u002Fconcurrency\u002Fconcurrent-futures",[4209,4213,4217,4221,4225,4229],{"id":4210,"difficulty":63,"q":4211,"a":4212},"executor-abstraction","What is the Executor abstraction in concurrent.futures?","`concurrent.futures` provides a **high-level**, uniform interface for running\ncallables asynchronously. An **`Executor`** manages a **pool of workers** and\nhands you back **`Future`** objects representing pending results — and the **same\nAPI** works whether the workers are threads or processes, so you can swap one for\nthe other with a one-line change.\n\n```python\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef work(x):\n    return x * 2\n\nwith ThreadPoolExecutor(max_workers=4) as ex:   # context manager auto-shuts down\n    future = ex.submit(work, 10)                # schedule the call\n    print(future.result())                      # 20\n\n# swap to processes by changing only the class name:\n# with ProcessPoolExecutor() as ex: ...\n```\n\nThe context manager (`with`) cleanly handles worker shutdown and waits for\npending work on exit. Rule of thumb: prefer `concurrent.futures` over raw\n`threading`\u002F`multiprocessing` when you just want to run a function over a pool\nand collect results.\n",{"id":4214,"difficulty":63,"q":4215,"a":4216},"thread-vs-process-pool","When do you use ThreadPoolExecutor vs ProcessPoolExecutor?","Both share the Executor API but differ in workers. **`ThreadPoolExecutor`** runs\ntasks in **threads** within one process — cheap, shared memory, but bound by the\n**GIL**, so it only helps **I\u002FO-bound** work. **`ProcessPoolExecutor`** runs tasks\nin **separate processes**, each with its own GIL, giving **true parallelism** for\n**CPU-bound** work (at the cost of pickling arguments\u002Fresults).\n\n```python\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\n\n# I\u002FO-bound: many network\u002Fdisk waits -> threads\nwith ThreadPoolExecutor() as ex:\n    ex.map(download, urls)\n\n# CPU-bound: number crunching -> processes\nwith ProcessPoolExecutor() as ex:\n    ex.map(crunch, datasets)\n```\n\nBecause the API is identical, you can prototype with threads and switch to\nprocesses if the GIL becomes the bottleneck. Rule of thumb: I\u002FO-bound ->\n`ThreadPoolExecutor`; CPU-bound -> `ProcessPoolExecutor`.\n",{"id":4218,"difficulty":63,"q":4219,"a":4220},"submit-and-futures","What does submit() return, and what is a Future?","**`submit(fn, *args)`** schedules `fn` to run in the pool and **immediately**\nreturns a **`Future`** — a handle to a result that may not exist yet. The Future\nlets you check status (`done()`, `running()`), **block for the result**\n(`result()`), retrieve an exception (`exception()`), `cancel()`, or attach a\ncallback (`add_done_callback`).\n\n```python\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef slow_double(x):\n    return x * 2\n\nwith ThreadPoolExecutor() as ex:\n    fut = ex.submit(slow_double, 21)   # returns instantly\n    print(fut.done())                  # False — probably still running\n    print(fut.result())                # 42 — blocks until ready\n```\n\n`result(timeout=...)` blocks (up to an optional timeout) until the value is\nready. A Future decouples **starting** the work from **collecting** it, which is\nwhat makes overlapping multiple calls possible.\n",{"id":4222,"difficulty":71,"q":4223,"a":4224},"executor-map","How does executor.map work and how does it differ from submit?","**`executor.map(fn, iterable)`** is the convenient bulk form: it applies `fn` to\nevery item concurrently and returns an **iterator of results in input order** —\nanalogous to the built-in `map`, but parallel. **`submit`** is lower level,\ngiving you a Future per call for fine-grained control.\n\n```python\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef fetch(url):\n    return len(url)\n\nurls = [\"a\", \"bb\", \"ccc\"]\nwith ThreadPoolExecutor() as ex:\n    for result in ex.map(fetch, urls):   # results stream back in order\n        print(result)                    # 1, 2, 3\n```\n\n`map` is great when you have a clean iterable and want **ordered** results with\nminimal code. Use `submit` (often with `as_completed`) when you need results\n**as they finish**, per-task error handling, or cancellation. Note `map` raises\nthe first exception when you iterate to that result.\n",{"id":4226,"difficulty":63,"q":4227,"a":4228},"as-completed","What does as_completed do?","**`as_completed(futures)`** yields each Future **as soon as it finishes**,\nregardless of submission order — so you can process results the moment they're\nready instead of waiting for the slowest task to keep its place (as `map`'s\nordered output would).\n\n```python\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef work(n):\n    return n * n\n\nwith ThreadPoolExecutor() as ex:\n    futures = [ex.submit(work, i) for i in range(5)]\n    for fut in as_completed(futures):     # whichever finishes first\n        print(fut.result())               # order is non-deterministic\n```\n\nThis is ideal for **responsiveness** — show progress as tasks complete, or\nhandle failures immediately. Use `map` when you want results in input order; use\n`as_completed` when you want them in **completion** order.\n",{"id":4230,"difficulty":63,"q":4231,"a":4232},"exception-propagation","How are exceptions handled with futures?","An exception raised inside a worker is **captured and stored** in its Future,\nnot raised at submit time. It **re-raises when you call `future.result()`** (or\niterate to that item in `map`). You can also inspect it without raising via\n**`future.exception()`**.\n\n```python\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef boom(x):\n    raise ValueError(f\"bad: {x}\")\n\nwith ThreadPoolExecutor() as ex:\n    fut = ex.submit(boom, 1)\n    err = fut.exception()        # returns the ValueError, doesn't raise\n    print(err)                   # bad: 1\n    fut.result()                 # NOW it re-raises ValueError\n```\n\nThe implication: if you never call `result()` (or check `exception()`), an\nerror can **pass silently**. Always retrieve results — typically in a `try\u002Fexcept`\naround `result()` — so worker failures surface in the main thread.\n",{"description":61},"Python interview questions on concurrent.futures: the Executor abstraction, ThreadPoolExecutor vs ProcessPoolExecutor, submit and Future objects, map, as_completed, and exception handling.","python\u002Fconcurrency\u002Fconcurrent-futures","concurrent.futures","EBXrpKsBJ9HKBfCU5qZ9GBoP7V5poZ4M3DOQAmPFiLQ",{"id":4239,"title":4240,"body":4241,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":4245,"navigation":66,"order":12,"path":4246,"questions":4247,"related":207,"seo":4267,"seoDescription":4268,"stem":4269,"subtopic":4270,"topic":4197,"topicSlug":371,"updated":214,"__hash__":4271},"qa\u002Fpython\u002Fconcurrency\u002Fgil.md","Gil",{"type":58,"value":4242,"toc":4243},[],{"title":61,"searchDepth":22,"depth":22,"links":4244},[],{},"\u002Fpython\u002Fconcurrency\u002Fgil",[4248,4252,4256,4260,4264],{"id":4249,"difficulty":84,"q":4250,"a":4251},"what-is-the-gil","What is the GIL?","The **Global Interpreter Lock** is a mutex in **CPython** that allows **only one\nthread to execute Python bytecode at a time**. Even on a multi-core machine, a\nmultithreaded pure-Python program runs its bytecode on **one core at a time** —\nthreads take turns holding the lock.\n\nIt exists to make CPython's memory management (especially **reference counting**)\nsimple and fast: without it, every refcount update would need its own lock. The\ninterpreter releases the GIL periodically and **around blocking I\u002FO** so other\nthreads can run.\n\n```python\nimport threading\n# both threads exist, but the GIL serializes their bytecode execution\ndef work():\n    total = 0\n    for _ in range(10_000_000):   # CPU-bound — holds the GIL\n        total += 1\n\nt1 = threading.Thread(target=work)\nt2 = threading.Thread(target=work)\nt1.start(); t2.start(); t1.join(); t2.join()   # ~no speedup vs one thread\n```\n\nWhy it matters: the GIL is a **CPython implementation detail** (not in the language\nspec, and absent in Jython\u002Fthe free-threaded 3.13+ build) that shapes when threads\ndo and don't help.\n",{"id":4253,"difficulty":63,"q":4254,"a":4255},"threading-vs-multiprocessing","What is the difference between threading and multiprocessing?","**Threads** share one process and one memory space, so they're cheap to create and\nshare data directly — but in CPython they're serialized by the **GIL**.\n**Processes** each have their own interpreter and memory, so they run on\n**separate cores in true parallel**, bypassing the GIL — at the cost of higher\nstartup overhead and needing to **serialize (pickle) data** to communicate.\n\n```python\nfrom threading import Thread\nfrom multiprocessing import Process\n\nThread(target=fn)    # shared memory, GIL-bound, light\nProcess(target=fn)   # separate memory, real parallelism, heavier\n```\n\nThreads communicate through shared objects (guarded by locks); processes\ncommunicate through `Queue`, `Pipe`, or shared-memory primitives because they don't\nshare state.\n\nRule of thumb: **threads for I\u002FO-bound** concurrency, **processes for CPU-bound**\nparallelism.\n",{"id":4257,"difficulty":84,"q":4258,"a":4259},"cpu-vs-io-bound","Why don't threads speed up CPU-bound work but help I\u002FO-bound work?","For **CPU-bound** work, threads are constantly executing bytecode, so they're\nalways contending for the **GIL** — only one runs at a time, and you get no\nparallel speedup (often a small slowdown from lock contention and context switches).\n\nFor **I\u002FO-bound** work, a thread that's waiting on the network, disk, or a database\nis **blocked outside the interpreter** — and CPython **releases the GIL during\nblocking I\u002FO**. So other threads run while one waits, giving real concurrency.\n\n```python\nimport requests, threading\n\ndef fetch(url):\n    requests.get(url)     # blocks on the network -> GIL released here\n\n# 10 threads overlap their waiting time -> much faster than sequential\nthreads = [threading.Thread(target=fetch, args=(u,)) for u in urls]\n```\n\nRule of thumb: if your bottleneck is **waiting**, use threads (or asyncio); if it's\n**computing**, use **processes** to get past the GIL.\n",{"id":4261,"difficulty":84,"q":4262,"a":4263},"race-conditions-locks","What is a race condition and how do locks prevent it?","A **race condition** occurs when two threads access shared mutable state and the\nresult depends on **timing**. Even `x += 1` is not atomic — it's read, add, write,\nand a thread can be switched out mid-sequence, so updates get lost.\n\nA **lock** (`threading.Lock`) creates a **critical section**: only the thread\nholding it can proceed, the rest wait, so the read-modify-write happens atomically.\nUsing `with lock:` guarantees the lock is always released, even on exceptions.\n\n```python\nimport threading\ncounter = 0\nlock = threading.Lock()\n\ndef increment():\n    global counter\n    for _ in range(100_000):\n        with lock:           # only one thread in here at a time\n            counter += 1     # now safe from lost updates\n```\n\nBeware over-locking: acquiring multiple locks in different orders can cause\n**deadlock**. Rule of thumb: guard **every** access to shared mutable state, keep\ncritical sections small, and prefer thread-safe `queue.Queue` for handoff.\n",{"id":4265,"difficulty":63,"q":4215,"a":4266},"threadpool-vs-processpool","Both come from `concurrent.futures` and share the same API — `submit` \u002F\n`map` returning `Future` objects — so you can swap them with one line. The\ndifference is the **worker type**: `ThreadPoolExecutor` runs tasks in **threads**\n(shared memory, GIL-bound) and `ProcessPoolExecutor` runs them in **separate\nprocesses** (true parallelism, pickled args).\n\n```python\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\n\n# I\u002FO-bound: many network\u002Ffile waits -> threads\nwith ThreadPoolExecutor(max_workers=20) as ex:\n    results = list(ex.map(download, urls))\n\n# CPU-bound: heavy computation -> processes (one per core)\nwith ProcessPoolExecutor() as ex:\n    results = list(ex.map(crunch_numbers, datasets))\n```\n\nUse **ThreadPoolExecutor for I\u002FO-bound** tasks (downloads, DB calls) where waiting\ndominates, and **ProcessPoolExecutor for CPU-bound** tasks to use all cores —\nremembering its arguments and return values must be **picklable**.\n\nRule of thumb: pick the executor by the bottleneck (waiting vs computing), and let\n`concurrent.futures` handle the pool lifecycle and result collection.\n",{"description":61},"Python interview questions on threading and the GIL — what the GIL is, threads vs multiprocessing, CPU-bound vs I\u002FO-bound work, race conditions and locks, and ThreadPoolExecutor vs ProcessPoolExecutor.","python\u002Fconcurrency\u002Fgil","Threading & the GIL","xnP8BJ-7TKpKC-39NQwkB1eRxm7A9hp5p5zsqHw6SWE",{"id":4273,"title":4274,"body":4275,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":4279,"navigation":66,"order":22,"path":4280,"questions":4281,"related":207,"seo":4306,"seoDescription":4307,"stem":4308,"subtopic":4274,"topic":4197,"topicSlug":371,"updated":214,"__hash__":4309},"qa\u002Fpython\u002Fconcurrency\u002Fmultiprocessing.md","Multiprocessing",{"type":58,"value":4276,"toc":4277},[],{"title":61,"searchDepth":22,"depth":22,"links":4278},[],{},"\u002Fpython\u002Fconcurrency\u002Fmultiprocessing",[4282,4286,4290,4294,4298,4302],{"id":4283,"difficulty":84,"q":4284,"a":4285},"multiprocessing-vs-threading","How does multiprocessing sidestep the GIL, and how is it different from threading?","**Threading** runs multiple threads inside **one process** that share one\ninterpreter — and therefore one **GIL** (Global Interpreter Lock), which lets\nonly one thread execute Python bytecode at a time. **Multiprocessing** spawns\n**separate OS processes**, each with its **own** interpreter and **own GIL**, so\nthey can run Python code in **true parallel** on multiple CPU cores.\n\n```python\nfrom multiprocessing import Process\nimport os\n\ndef work():\n    print(f\"running in pid {os.getpid()}\")  # a distinct process each time\n\nif __name__ == \"__main__\":            # required guard on Windows\u002Fspawn\n    ps = [Process(target=work) for _ in range(4)]\n    for p in ps: p.start()\n    for p in ps: p.join()\n```\n\nThe tradeoff: processes don't share memory, so passing data costs\n**serialization (pickling) and IPC overhead**, and each process has higher\nstartup cost than a thread. Rule of thumb: reach for multiprocessing when you\nneed real CPU parallelism, not just concurrency.\n",{"id":4287,"difficulty":63,"q":4288,"a":4289},"process-vs-pool","What is the difference between Process and Pool?","A **`Process`** represents a **single** child process you start and join\nmanually — good when you have a fixed, small number of distinct tasks. A\n**`Pool`** manages a **reusable group of worker processes** and hands out work\nto them, which is far more convenient for **many homogeneous tasks** over a\ndataset.\n\n```python\nfrom multiprocessing import Pool\n\ndef square(n):\n    return n * n\n\nif __name__ == \"__main__\":\n    with Pool(processes=4) as pool:\n        results = pool.map(square, range(10))   # distributed across 4 workers\n    print(results)   # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n```\n\n`Pool` reuses workers (amortizing startup cost) and offers `map`, `imap`,\n`apply_async`, etc. Use `Process` for a few long-lived distinct jobs; use `Pool`\nwhen you're fanning the same function over many inputs.\n",{"id":4291,"difficulty":84,"q":4292,"a":4293},"ipc-queue-pipe","How do processes communicate (Queue vs Pipe)?","Because processes don't share memory, they communicate through **IPC**\nprimitives. A **`Queue`** is a **multi-producer\u002Fmulti-consumer**, thread- and\nprocess-safe FIFO — the general-purpose choice. A **`Pipe`** is a faster but\nlower-level **two-endpoint** connection, best for communication between exactly\n**two** processes.\n\n```python\nfrom multiprocessing import Process, Queue\n\ndef producer(q):\n    q.put(\"result\")          # values are pickled across the boundary\n\nif __name__ == \"__main__\":\n    q = Queue()\n    p = Process(target=producer, args=(q,))\n    p.start()\n    print(q.get())           # \"result\"\n    p.join()\n```\n\nBoth serialize objects under the hood, so only **picklable** data flows through\nthem. Use `Queue` for fan-in\u002Ffan-out among many workers; use `Pipe` for a tight\none-to-one channel where you want the lower overhead.\n",{"id":4295,"difficulty":84,"q":4296,"a":4297},"pickling-overhead","What is the pickling overhead, and what can't be pickled?","Every argument and return value crossing a process boundary must be\n**serialized with `pickle`**, sent, then **deserialized** on the other side.\nFor large objects this **copying cost can dwarf the parallelism gains**, and\nsome objects simply **can't be pickled**.\n\n```python\nimport pickle\n\npickle.dumps(lambda x: x)   # PicklingError — lambdas aren't picklable\n# Also unpicklable: open file handles, sockets, locks, db connections,\n# local\u002Fnested functions, and generators.\n```\n\nPicklable things include module-level functions and classes, and basic\ncontainers of picklable values. The practical implications: pass **small,\npicklable** payloads, define worker functions at **module top level**, and\navoid shipping huge data structures between processes. Minimizing what crosses\nthe boundary is the key to multiprocessing performance.\n",{"id":4299,"difficulty":84,"q":4300,"a":4301},"shared-state","How do you share state between processes?","Since each process has its own memory, you need explicit shared-state tools.\n**`Value`** and **`Array`** put simple data in **shared memory** (fast, but\nlimited types and you must guard with a lock). A **`Manager`** hosts richer\nshared objects (`dict`, `list`, etc.) via a **server process** — more flexible\nbut slower because access is proxied.\n\n```python\nfrom multiprocessing import Process, Value, Lock\n\ndef inc(counter, lock):\n    for _ in range(1000):\n        with lock:               # protect the shared value\n            counter.value += 1\n\nif __name__ == \"__main__\":\n    counter = Value(\"i\", 0)      # shared int in shared memory\n    lock = Lock()\n    ps = [Process(target=inc, args=(counter, lock)) for _ in range(4)]\n    for p in ps: p.start()\n    for p in ps: p.join()\n    print(counter.value)         # 4000\n```\n\nPrefer **message passing** (Queue\u002FPipe) over shared state when you can — it's\neasier to reason about. Reach for `Value`\u002F`Array` for hot, simple counters and a\n`Manager` only when you genuinely need shared complex objects.\n",{"id":4303,"difficulty":63,"q":4304,"a":4305},"when-multiprocessing","When should you use multiprocessing instead of threads or asyncio?","Use multiprocessing for **CPU-bound** work — number crunching, image\nprocessing, data transforms — where you need to **saturate multiple cores** with\nPython code. Threads and asyncio can't do that because the **GIL** serializes\nbytecode execution; only separate processes get separate GILs.\n\n```python\nfrom multiprocessing import Pool\n\ndef heavy(n):                      # pure-Python CPU work\n    return sum(i * i for i in range(n))\n\nif __name__ == \"__main__\":\n    with Pool() as pool:           # defaults to os.cpu_count() workers\n        print(pool.map(heavy, [10_000_000] * 8))   # runs in parallel\n```\n\nFor **I\u002FO-bound** work (network, disk, DB), threads or asyncio are usually\nbetter — they're cheaper and the GIL is released during I\u002FO anyway. Rule of\nthumb: CPU-bound -> multiprocessing; I\u002FO-bound -> threads\u002Fasyncio.\n",{"description":61},"Python interview questions on the multiprocessing module: how it sidesteps the GIL, Process vs Pool, IPC with Queue\u002FPipe, pickling limits, and shared state.","python\u002Fconcurrency\u002Fmultiprocessing","q6g-NDE__tlhDOdIPbX1WLFlzxD4custMmavX-rPQ3s",{"id":4311,"title":4312,"body":4313,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4317,"navigation":66,"order":50,"path":4318,"questions":4319,"related":207,"seo":4344,"seoDescription":4345,"stem":4346,"subtopic":4347,"topic":4348,"topicSlug":4349,"updated":214,"__hash__":4350},"qa\u002Fpython\u002Fdata-structures\u002Fcollections-module.md","Collections Module",{"type":58,"value":4314,"toc":4315},[],{"title":61,"searchDepth":22,"depth":22,"links":4316},[],{},"\u002Fpython\u002Fdata-structures\u002Fcollections-module",[4320,4324,4328,4332,4336,4340],{"id":4321,"difficulty":71,"q":4322,"a":4323},"counter","What is collections.Counter and what is it good for?","**`Counter`** is a `dict` subclass for **counting hashable items**. You pass it\nany iterable and it tallies occurrences into a `{element: count}` mapping, with\nhandy extras like `most_common()`. Missing keys return **0** instead of raising.\n\n```python\nfrom collections import Counter\nc = Counter(\"mississippi\")\n# Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})\n\nc.most_common(2)     # [('i', 4), ('s', 4)] — top N by count\nc[\"z\"]               # 0 — missing key, no KeyError\nc.update(\"pp\")       # add more counts -> p becomes 4\n\nCounter([1, 1, 2]) + Counter([1, 3])   # Counter({1: 3, 2: 1, 3: 1})\n```\n\nIt replaces the manual `d[x] = d.get(x, 0) + 1` pattern and supports arithmetic\nbetween counters. Reach for `Counter` whenever the task is \"how many of each?\" —\nword frequencies, tallies, or finding the most common elements.\n",{"id":4325,"difficulty":71,"q":4326,"a":4327},"defaultdict","How does collections.defaultdict work, and how is it different from dict.setdefault?","**`defaultdict(factory)`** is a `dict` that **auto-creates a missing key's value**\nby calling the zero-argument `factory` (like `list`, `int`, or `set`) the first\ntime you access it — so you can append or increment without initializing.\n\n```python\nfrom collections import defaultdict\n\ngroups = defaultdict(list)\ngroups[\"fruits\"].append(\"apple\")   # key auto-created as [] then appended\n# {'fruits': ['apple']}\n\ncounts = defaultdict(int)\nfor ch in \"aab\":\n    counts[ch] += 1                # missing keys start at 0\n# {'a': 2, 'b': 1}\n```\n\nThe difference from **`setdefault`**: `setdefault` evaluates its default\n**on every call** even when the key exists (wasteful), whereas `defaultdict`\nonly calls the factory **on a miss**. Use `defaultdict` for grouping and\ncounting loops; use plain `setdefault` for a one-off default insertion.\n",{"id":4329,"difficulty":63,"q":4330,"a":4331},"deque","What is a collections.deque and why use it over a list?","A **`deque`** (\"double-ended queue\") gives **O(1) appends and pops at *both*\nends**, whereas a `list` is O(n) for operations at the front (every element\nshifts). It also supports a **`maxlen`** for a fixed-size sliding window.\n\n```python\nfrom collections import deque\n\nd = deque([1, 2, 3])\nd.appendleft(0)    # O(1) — list.insert(0, x) would be O(n)\nd.append(4)        # O(1)\nd.popleft()        # O(1) — efficient FIFO queue\n\nwindow = deque(maxlen=3)\nfor x in [1, 2, 3, 4]:\n    window.append(x)   # auto-drops from the left\n# deque([2, 3, 4], maxlen=3)\n```\n\nUse a deque for **queues, BFS, and sliding windows**; with `maxlen` it\nauto-discards the oldest item when full (great for \"last N\" buffers). Stick with\na list when you only push\u002Fpop at the end or need fast random indexing.\n",{"id":4333,"difficulty":63,"q":4334,"a":4335},"ordereddict","Is OrderedDict still useful now that regular dicts keep insertion order (3.7+)?","Mostly not for ordering itself — since **Python 3.7** a plain `dict` already\npreserves insertion order, so `OrderedDict` is no longer needed just to remember\norder. But it still has a couple of **distinct features** a regular dict lacks.\n\n```python\nfrom collections import OrderedDict\n\n# 1) order-sensitive equality\nOrderedDict(a=1, b=2) == OrderedDict(b=2, a=1)   # False\ndict(a=1, b=2)        == dict(b=2, a=1)          # True (order ignored)\n\n# 2) move_to_end and a popitem(last=...) toggle\nod = OrderedDict(a=1, b=2, c=3)\nod.move_to_end(\"a\")        # OrderedDict([('b',2),('c',3),('a',1)])\nod.popitem(last=False)     # pop from the FRONT — FIFO\n```\n\nSo use `OrderedDict` when you need **order-sensitive `==`**, **`move_to_end`**,\nor **`popitem(last=False)`** — for example, building an LRU cache. For plain\n\"keep the order I inserted,\" a regular dict is now enough.\n",{"id":4337,"difficulty":63,"q":4338,"a":4339},"chainmap","What is collections.ChainMap?","**`ChainMap`** groups multiple dicts into a **single, layered view** without\ncopying them. Lookups search the underlying mappings **in order** and return the\nfirst match, so earlier maps **shadow** later ones.\n\n```python\nfrom collections import ChainMap\n\ndefaults = {\"color\": \"red\", \"size\": \"M\"}\noverrides = {\"color\": \"blue\"}\nsettings = ChainMap(overrides, defaults)\n\nsettings[\"color\"]    # 'blue' — first map wins\nsettings[\"size\"]     # 'M'    — falls through to defaults\n\nsettings[\"size\"] = \"L\"   # writes go to the FIRST map (overrides) only\n```\n\nIt's perfect for **layered configuration** (CLI args over env vars over\ndefaults) and scope-like lookups, because it stays live — changing a source dict\nshows up immediately. Note that **writes and deletes only affect the first\nmapping**. Use it to merge config layers without flattening them into one dict.\n",{"id":4341,"difficulty":71,"q":4342,"a":4343},"namedtuple-crossref","How does namedtuple fit into the collections module?","**`collections.namedtuple`** is a factory that creates an **immutable tuple\nsubclass with named fields** — lightweight, hashable records that read like\nobjects but behave like tuples (indexing, unpacking, comparison).\n\n```python\nfrom collections import namedtuple\n\nPoint = namedtuple(\"Point\", [\"x\", \"y\"])\np = Point(3, 4)\np.x, p[0]        # 3, 3  — named and positional access\np._asdict()      # {'x': 3, 'y': 4}\np._replace(x=9)  # Point(x=9, y=4) — returns a NEW tuple (immutable)\n```\n\nIt rounds out the module's record-like tools alongside `Counter`,\n`defaultdict`, and `deque`. For richer needs — type hints, defaults, methods —\n`typing.NamedTuple` or a `@dataclass` is the modern choice. Use `namedtuple` for\nsimple, immutable, self-documenting records.\n",{"description":61},"Python interview questions on the collections module — Counter, defaultdict, deque, OrderedDict, ChainMap, and how they relate to namedtuple.","python\u002Fdata-structures\u002Fcollections-module","The collections Module","Data Structures","data-structures","LZW7rGcpTd9BsXIZIOFd-X_5qK8sKAY3AZmE-BjNbyY",{"id":4352,"title":4353,"body":4354,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4358,"navigation":66,"order":31,"path":4359,"questions":4360,"related":207,"seo":4385,"seoDescription":4386,"stem":4387,"subtopic":4353,"topic":4348,"topicSlug":4349,"updated":214,"__hash__":4388},"qa\u002Fpython\u002Fdata-structures\u002Fdictionaries.md","Dictionaries",{"type":58,"value":4355,"toc":4356},[],{"title":61,"searchDepth":22,"depth":22,"links":4357},[],{},"\u002Fpython\u002Fdata-structures\u002Fdictionaries",[4361,4365,4369,4373,4377,4381],{"id":4362,"difficulty":71,"q":4363,"a":4364},"insertion-ordering","Are Python dictionaries ordered?","Yes. Since **Python 3.7**, dictionaries **preserve insertion order** as a\n**language guarantee** — iterating a dict yields keys in the order they were\nfirst added. (This was an implementation detail in CPython 3.6, then made\nofficial in 3.7.)\n\n```python\nd = {}\nd[\"b\"] = 1\nd[\"a\"] = 2\nd[\"c\"] = 3\nlist(d)            # ['b', 'a', 'c'] — insertion order, not sorted\n\nd[\"b\"] = 9         # updating a value does NOT change order\nlist(d)            # ['b', 'a', 'c']\n```\n\nNote that **updating** an existing key keeps its original position; only the\nfirst insertion fixes the order. Reassigning doesn't move it. Because ordering\nis guaranteed, plain `dict` now covers most cases that once needed\n`OrderedDict`.\n",{"id":4366,"difficulty":71,"q":4367,"a":4368},"get-vs-bracket-setdefault","What is the difference between d[key], d.get(key), and d.setdefault()?","**`d[key]`** raises `KeyError` if the key is missing. **`d.get(key, default)`**\nreturns a default (or `None`) instead of raising — a safe read.\n**`d.setdefault(key, default)`** returns the existing value if present, but if\nmissing it **inserts** the default and returns it.\n\n```python\nd = {\"a\": 1}\nd[\"b\"]               # KeyError\nd.get(\"b\")           # None — no error\nd.get(\"b\", 0)        # 0   — supplied default\n\nd.setdefault(\"a\", 99)  # 1  — already present, unchanged\nd.setdefault(\"c\", []).append(5)  # inserts c=[], then appends -> {'c': [5]}\n```\n\nUse `get` for a safe lookup that **doesn't mutate**, and `setdefault` to\n**read-or-initialize** in one step (handy for grouping). For heavy grouping work,\n`collections.defaultdict` is usually cleaner.\n",{"id":4370,"difficulty":63,"q":4371,"a":4372},"merging-dicts","What are the ways to merge two dictionaries?","The modern way is the **`|` merge operator** (Python 3.9+), which returns a new\ndict; **`|=`** merges in place. Before 3.9, the idiom was **`{**a, **b}`\nunpacking**, and `dict.update()` merges in place.\n\n```python\na = {\"x\": 1, \"y\": 2}\nb = {\"y\": 9, \"z\": 3}\n\na | b           # {'x': 1, 'y': 9, 'z': 3}  — new dict (3.9+)\n{**a, **b}      # {'x': 1, 'y': 9, 'z': 3}  — same, works pre-3.9\n\na.update(b)     # mutates a in place -> {'x': 1, 'y': 9, 'z': 3}\n```\n\nIn every approach the **right-hand dict wins** on key collisions (`y` becomes\n`9`). Use `|` for a clean new dict on modern Python, `{**a, **b}` for\ncompatibility, and `update()`\u002F`|=` when you want to mutate in place.\n",{"id":4374,"difficulty":63,"q":4375,"a":4376},"keys-values-items-views","What do keys(), values(), and items() return, and what is a view object?","They return **view objects** — dynamic, read-only windows onto the dict that\n**reflect changes live** rather than copying the data. They're iterable and\nsupport set-like operations, but they're not lists.\n\n```python\nd = {\"a\": 1, \"b\": 2}\nkeys = d.keys()\nd[\"c\"] = 3\nlist(keys)          # ['a', 'b', 'c'] — view updated automatically!\n\nkeys[0]             # TypeError — a view isn't indexable\nlist(d.keys())      # ['a', 'b', 'c'] — materialize when you need a list\n\nd.keys() & {\"a\"}    # {'a'} — keys views support set operations\n```\n\nBecause a view is **live**, it's memory-cheap but you must `list(...)` it to\nindex or snapshot it. Also avoid mutating the dict's size while iterating a view\n— that raises `RuntimeError`. Use views to iterate efficiently; copy to a list\nwhen you need a stable, indexable sequence.\n",{"id":4378,"difficulty":63,"q":4379,"a":4380},"keys-hashable-lookup","Why must dictionary keys be hashable, and why are lookups O(1)?","A dict is a **hash table**: it computes `hash(key)` to decide which bucket the\nentry lives in, giving **average O(1)** insertion and lookup regardless of size.\nFor this to work, a key's hash must **never change**, so keys must be\n**hashable** — effectively **immutable**.\n\n```python\nd = {}\nd[(1, 2)] = \"ok\"     # tuple is immutable -> hashable\nd[[1, 2]] = \"no\"     # TypeError: unhashable type: 'list'\n\n# O(1): lookup time doesn't grow with the dict's size\n\"x\" in d             # hashes \"x\", checks one bucket — not a full scan\n```\n\nIf a mutable key could change after insertion, its hash would change and the\nentry would land in the wrong bucket — you'd never find it again. That's why\nlists, dicts, and sets can't be keys, but tuples and frozensets can. The\nhash-table design is exactly what makes membership tests near-instant.\n",{"id":4382,"difficulty":71,"q":4383,"a":4384},"dict-comprehension","What is a dict comprehension?","A **dict comprehension** builds a dictionary in one expression using\n`{key: value for item in iterable}`, optionally with a filtering `if`. It's the\nconcise, readable alternative to a `for` loop that calls `d[k] = v`.\n\n```python\nsquares = {n: n * n for n in range(5)}\n# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n\nprices = {\"apple\": 3, \"pear\": 0, \"fig\": 7}\nin_stock = {k: v for k, v in prices.items() if v > 0}\n# {'apple': 3, 'fig': 7}\n\ninverted = {v: k for k, v in prices.items()}   # swap keys\u002Fvalues\n```\n\nLike other comprehensions it has its **own scope** (no leaked loop variable) and\nis generally faster than the equivalent loop. Use it to transform, filter, or\ninvert mappings clearly — but keep it readable rather than cramming in logic.\n",{"description":61},"Python interview questions on dict insertion ordering, get vs bracket access, setdefault, merging dicts, view objects, why keys must be hashable, and dict comprehensions.","python\u002Fdata-structures\u002Fdictionaries","LzhuhDxYYShbZNpJ1GNHVfGL3cDVdrMl9q-LhVisbXs",{"id":4390,"title":4391,"body":4392,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4396,"navigation":66,"order":12,"path":4397,"questions":4398,"related":207,"seo":4419,"seoDescription":4420,"stem":4421,"subtopic":4422,"topic":4348,"topicSlug":4349,"updated":214,"__hash__":4423},"qa\u002Fpython\u002Fdata-structures\u002Flists.md","Lists",{"type":58,"value":4393,"toc":4394},[],{"title":61,"searchDepth":22,"depth":22,"links":4395},[],{},"\u002Fpython\u002Fdata-structures\u002Flists",[4399,4403,4407,4411,4415],{"id":4400,"difficulty":63,"q":4401,"a":4402},"list-vs-array","What is the difference between a Python list and an array?","A **`list`** is Python's built-in, **dynamically-sized, heterogeneous**\ncontainer — it can hold objects of any type because each slot stores a\n**reference** to a boxed Python object. The standard-library **`array.array`**\n(and NumPy's `ndarray`) is **homogeneous and typed**, storing raw C values\ncontiguously, which is far more **memory-efficient** for large numeric data.\n\n```python\nfrom array import array\nnums = [1, 2, \"three\"]      # list — mixed types allowed\ntyped = array(\"i\", [1, 2, 3])  # array — all C ints, compact\ntyped.append(\"x\")           # TypeError — type-checked\n\nimport sys\nsys.getsizeof([1, 2, 3])    # bigger: stores pointers\nsys.getsizeof(array(\"i\", [1, 2, 3]))  # smaller: packed ints\n```\n\nRule of thumb: reach for a plain **`list`** for general-purpose, mixed-type\ncollections; use **`array`** or **NumPy** when you have large amounts of\nuniform numeric data and care about memory or vectorized speed.\n",{"id":4404,"difficulty":63,"q":4405,"a":4406},"slicing-semantics","How does list slicing work, including negative steps?","A slice is `lst[start:stop:step]`. `start` is **inclusive**, `stop` is\n**exclusive**, and any part can be **omitted** (defaults: start of list, end of\nlist, step 1). A **negative step** walks the list **backwards**, and when it's\nnegative the defaults for `start`\u002F`stop` flip to the **end** and the\n**beginning**.\n\n```python\na = [0, 1, 2, 3, 4, 5]\na[1:4]      # [1, 2, 3]   — stop is exclusive\na[:3]       # [0, 1, 2]   — omitted start = 0\na[::2]      # [0, 2, 4]   — every other element\na[::-1]     # [5, 4, 3, 2, 1, 0]  — reversed copy\na[4:1:-1]   # [4, 3, 2]   — backwards, stop exclusive\n```\n\nSlicing **never raises** for out-of-range indices (`a[10:20]` is just `[]`),\nunlike single-element indexing. Remember `a[::-1]` is the idiomatic way to get a\n**reversed shallow copy**.\n",{"id":4408,"difficulty":63,"q":4409,"a":4410},"append-extend-insert","What is the difference between append, extend, and insert?","**`append(x)`** adds a single item to the end in **amortized O(1)**.\n**`extend(iterable)`** adds **each element** of an iterable to the end (also\namortized O(1) per element). **`insert(i, x)`** places an item at index `i`,\nwhich is **O(n)** because every following element must shift right.\n\n```python\na = [1, 2, 3]\na.append([4, 5])   # [1, 2, 3, [4, 5]]  — the LIST is one element\na = [1, 2, 3]\na.extend([4, 5])   # [1, 2, 3, 4, 5]    — unpacks the iterable\na.insert(0, 99)    # [99, 1, 2, 3, 4, 5] — O(n) shift\n```\n\nThe classic trap: `append([4, 5])` nests the whole list as one item, whereas\n`extend([4, 5])` merges its elements. Avoid `insert(0, …)` in a loop — it's\nO(n) each time; use `collections.deque` for fast front insertion.\n",{"id":4412,"difficulty":63,"q":4413,"a":4414},"comprehension-vs-loop","Are list comprehensions faster than equivalent for loops?","Usually **yes**. A comprehension runs its iteration in **optimized C-level\nbytecode** and avoids the repeated `list.append` **attribute lookup and method\ncall** that a manual loop incurs, so it's typically **20–40% faster** as well as\nmore concise. It also creates the loop variable in its **own scope**, so it\ndoesn't leak.\n\n```python\n# manual loop — explicit append each iteration\nsquares = []\nfor n in range(1000):\n    squares.append(n * n)\n\n# comprehension — faster and clearer\nsquares = [n * n for n in range(1000)]\n```\n\nUse a comprehension when you're **building a list** from an expression. But if\nthe body has side effects or grows complex (nested conditionals, multiple\nstatements), a readable `for` loop is the better choice — clarity beats a small\nspeed win.\n",{"id":4416,"difficulty":71,"q":4417,"a":4418},"sort-vs-sorted","What is the difference between list.sort() and sorted()?","**`list.sort()`** sorts a list **in place** and returns **`None`** — it mutates\nthe original and only works on lists. **`sorted(iterable)`** returns a **new\nsorted list** and leaves the input untouched, accepting **any iterable** (tuples,\nsets, generators, dict keys).\n\n```python\nnums = [3, 1, 2]\nresult = nums.sort()        # result is None! nums is now [1, 2, 3]\n\noriginal = (3, 1, 2)\nnew = sorted(original)      # new = [1, 2, 3], original unchanged\nsorted([\"bb\", \"a\"], key=len, reverse=True)  # ['bb', 'a']\n```\n\nBoth are **stable** (equal elements keep their order) and run in **O(n log n)**\n(Timsort). Watch the gotcha: `x = mylist.sort()` leaves `x` as `None`. Use\n`sort()` to save memory when you don't need the original; use `sorted()` when you\nmust preserve it or are sorting a non-list iterable.\n",{"description":61},"Python interview questions on lists vs arrays, slicing semantics and negative steps, append vs extend vs insert, comprehensions, and sort vs sorted.","python\u002Fdata-structures\u002Flists","Lists & Slicing","UKHUEr1MtYNcjg937qLbMk2iR2kGGF2n3zhJyYXTljY",{"id":4425,"title":4426,"body":4427,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4431,"navigation":66,"order":40,"path":4432,"questions":4433,"related":207,"seo":4458,"seoDescription":4459,"stem":4460,"subtopic":4461,"topic":4348,"topicSlug":4349,"updated":214,"__hash__":4462},"qa\u002Fpython\u002Fdata-structures\u002Fsets.md","Sets",{"type":58,"value":4428,"toc":4429},[],{"title":61,"searchDepth":22,"depth":22,"links":4430},[],{},"\u002Fpython\u002Fdata-structures\u002Fsets",[4434,4438,4442,4446,4450,4454],{"id":4435,"difficulty":71,"q":4436,"a":4437},"set-operations","What are the main set operations in Python?","Sets support the classic mathematical operations, each with an **operator** and\nan equivalent **method**: **union** (`|`), **intersection** (`&`),\n**difference** (`-`), and **symmetric difference** (`^`, items in exactly one\nset).\n\n```python\na = {1, 2, 3}\nb = {2, 3, 4}\n\na | b    # {1, 2, 3, 4}      union — in either\na & b    # {2, 3}            intersection — in both\na - b    # {1}               difference — in a, not b\na ^ b    # {1, 4}            symmetric difference — in one, not both\n\na.union(b)              # method form, accepts any iterable\na.intersection([2, 3])  # b can be a list here\n```\n\nThe **operator** forms require both operands to be sets, while the **method**\nforms accept any iterable. Use them for fast \"what's common \u002F unique \u002F missing\"\nquestions instead of nested loops.\n",{"id":4439,"difficulty":63,"q":4440,"a":4441},"set-vs-list-membership","Why is membership testing faster in a set than a list?","A `set` is backed by a **hash table**, so `x in s` is **average O(1)** — it\nhashes `x` and checks one bucket. A `list` has no such index, so `x in lst` is\n**O(n)** — it scans elements one by one until it finds a match or reaches the\nend.\n\n```python\nbig_list = list(range(1_000_000))\nbig_set  = set(big_list)\n\n999_999 in big_list   # O(n) — scans up to a million items\n999_999 in big_set    # O(1) — single hash lookup\n```\n\nFor repeated membership checks over a large collection, converting to a set\nfirst is a huge win. The trade-off is that sets are **unordered** and elements\nmust be **hashable**. Rule of thumb: if you mostly ask \"is X in here?\", use a\nset, not a list.\n",{"id":4443,"difficulty":71,"q":4444,"a":4445},"dedup-with-set","How do you remove duplicates from a list using a set?","Wrapping a list in **`set()`** removes duplicates instantly, since a set can't\nhold repeated values. The catch is that a set is **unordered**, so this doesn't\npreserve the original order.\n\n```python\nnums = [3, 1, 2, 3, 1]\nunique = list(set(nums))      # e.g. [1, 2, 3] — order NOT guaranteed\n\n# order-preserving dedup (dict keys are unique AND ordered since 3.7):\nordered = list(dict.fromkeys(nums))   # [3, 1, 2]\n```\n\nUse `set()` when you only care about the **distinct values**; when order\nmatters, use **`dict.fromkeys()`**, which keeps first-seen order thanks to\nguaranteed dict ordering. Both require the elements to be hashable.\n",{"id":4447,"difficulty":71,"q":4448,"a":4449},"add-discard-remove","What is the difference between add, discard, and remove on a set?","**`add(x)`** inserts an element (a no-op if it's already present). To delete,\n**`remove(x)`** raises `KeyError` if the element is missing, while\n**`discard(x)`** removes it **silently** if present and does nothing otherwise.\n\n```python\ns = {1, 2, 3}\ns.add(2)          # already there — no change\ns.add(4)          # {1, 2, 3, 4}\n\ns.remove(4)       # {1, 2, 3}\ns.remove(99)      # KeyError — not in set\ns.discard(99)     # no error, no change\ns.pop()           # removes and returns an arbitrary element\n```\n\nChoose **`discard`** when \"remove if it's there\" is the intent (no need to guard\nwith a membership check), and **`remove`** when a missing element is genuinely an\nerror you want surfaced. `pop()` removes an arbitrary element since sets are\nunordered.\n",{"id":4451,"difficulty":63,"q":4452,"a":4453},"frozenset","What is a frozenset and when do you need one?","A **`frozenset`** is the **immutable** version of `set` — it supports all the\nread operations (union, intersection, membership) but has **no `add`\u002F`remove`**.\nBecause it's immutable, it's **hashable**, so it can be a **dict key** or an\n**element of another set**.\n\n```python\nfs = frozenset([1, 2, 3])\nfs.add(4)              # AttributeError — immutable\nfs & {2, 3, 4}         # frozenset({2, 3}) — set ops still work\n\n{fs: \"a group\"}        # usable as a dict key\n{frozenset({1, 2}), frozenset({3, 4})}   # a set OF sets\n```\n\nThe classic use is a **set of sets**: regular sets are unhashable, so the inner\nones must be frozensets. Also use a frozenset for a constant collection you want\nto guarantee can't be mutated. Reach for it whenever you need a set-like value\nthat must be hashable.\n",{"id":4455,"difficulty":71,"q":4456,"a":4457},"set-comprehension","What is a set comprehension?","A **set comprehension** builds a set in one expression with\n`{expr for item in iterable}`, automatically **deduplicating** the results. It's\nthe set sibling of list and dict comprehensions, with curly braces and no\n`key:value` pair.\n\n```python\nsquares = {n * n for n in range(-3, 4)}\n# {0, 1, 4, 9} — note 9 appears once even though -3 and 3 both map to it\n\nwords = [\"Hi\", \"hi\", \"HEY\"]\nlowered = {w.lower() for w in words}   # {'hi', 'hey'}\n```\n\nIt's ideal when you want **unique transformed values** in a single readable step.\nWatch out that `{}` alone is an **empty dict**, not an empty set — use `set()`\nfor an empty set. Use a set comprehension when both transformation and\ndeduplication are the goal.\n",{"description":61},"Python interview questions on set operations, O(1) membership vs lists, deduplication, add\u002Fdiscard\u002Fremove, frozensets, and set comprehensions.","python\u002Fdata-structures\u002Fsets","Sets & Frozensets","cTcBrrIA7tgVyW4p3hQf_V6QjLhZcf7eBJuL-k_iHL0",{"id":4464,"title":4465,"body":4466,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4470,"navigation":66,"order":22,"path":4471,"questions":4472,"related":207,"seo":4493,"seoDescription":4494,"stem":4495,"subtopic":4496,"topic":4348,"topicSlug":4349,"updated":214,"__hash__":4497},"qa\u002Fpython\u002Fdata-structures\u002Ftuples.md","Tuples",{"type":58,"value":4467,"toc":4468},[],{"title":61,"searchDepth":22,"depth":22,"links":4469},[],{},"\u002Fpython\u002Fdata-structures\u002Ftuples",[4473,4477,4481,4485,4489],{"id":4474,"difficulty":71,"q":4475,"a":4476},"tuple-vs-list","What is the difference between a tuple and a list, and when should you use each?","A **`list`** is **mutable** and variable-length — use it for a **homogeneous,\nchanging** collection you add to, remove from, or reorder. A **`tuple`** is\n**immutable** and fixed — use it for a **heterogeneous, fixed record** whose\nshape won't change, like a coordinate or a database row.\n\n```python\nscores = [90, 85, 70]   # changing collection -> list\nscores.append(60)       # fine\n\npoint = (3, 4)          # fixed record -> tuple\npoint[0] = 9            # TypeError — tuples are immutable\n```\n\nTuples are also slightly **faster and more memory-efficient**, and because\nthey're **hashable** they can serve as dict keys or set members (a list can't).\nRule of thumb: reach for a tuple when the data is a fixed bundle that shouldn't\nchange, and a list when you need to mutate the collection.\n",{"id":4478,"difficulty":71,"q":4479,"a":4480},"packing-unpacking","What are tuple packing and unpacking, and how do you write a single-element tuple?","**Packing** collects several values into one tuple — the parentheses are often\noptional. **Unpacking** spreads a tuple's items into separate names in one\nassignment, which is how you return and receive multiple values cleanly.\n\n```python\nt = 1, 2, 3          # packing (parentheses optional)\na, b, c = t          # unpacking -> a=1, b=2, c=3\nfirst, *rest = t     # extended unpacking -> first=1, rest=[2, 3]\n\none = (5)            # NOT a tuple — just int 5 in parentheses\none = (5,)           # a 1-element tuple — the trailing comma makes it\n```\n\nThe key gotcha is the **single-element tuple**: it's the **trailing comma**, not\nthe parentheses, that creates a tuple — `(5)` is just the integer `5`, while\n`(5,)` is a one-tuple. When in doubt, the comma is what defines a tuple.\n",{"id":4482,"difficulty":63,"q":4483,"a":4484},"shallow-immutability","Is a tuple's immutability deep? Can a tuple contain mutable objects?","A tuple's **immutability is shallow**. You can't reassign or resize its slots,\nbut each slot just holds a **reference** — and if that reference points to a\nmutable object (like a list), that object can still be changed in place.\n\n```python\nt = (1, [2, 3])\nt[1].append(4)     # allowed — mutating the list inside the tuple\nprint(t)           # (1, [2, 3, 4])\n\nt[1] = [9]         # TypeError — can't reassign a tuple slot\n```\n\nA consequence interviewers love: a tuple that contains a list is **not\nhashable**, because hashability requires every element to be immutable too —\nso `hash((1, [2]))` raises `TypeError`. Bottom line: the tuple's structure is\nfrozen, but the objects it points to may not be.\n",{"id":4486,"difficulty":63,"q":4487,"a":4488},"namedtuple","What is a namedtuple and how does collections.namedtuple compare to typing.NamedTuple?","A **namedtuple** is an **immutable** tuple subclass with **named fields** —\ngiving you readable, hashable, lightweight records that still behave like\ntuples (index access, unpacking, comparison). There are two ways to define one.\n\n```python\nfrom collections import namedtuple\nPoint = namedtuple(\"Point\", [\"x\", \"y\"])\np = Point(3, 4)\np.x, p[0]        # 3, 3  — named AND index access\np.x = 9          # AttributeError — immutable\n\nfrom typing import NamedTuple\nclass Point(NamedTuple):     # class syntax with type hints + defaults\n    x: int\n    y: int = 0\n```\n\nThe `collections` form is concise; the `typing.NamedTuple` class form adds\n**type annotations, defaults, and the ability to add methods**. Use a namedtuple\nfor small fixed records when you want clarity over a bare tuple; reach for a\n`@dataclass` when you need mutability or richer behavior.\n",{"id":4490,"difficulty":63,"q":4491,"a":4492},"tuple-dict-key","Why can a tuple be used as a dictionary key when a list cannot?","Dict keys and set members must be **hashable**, which in practice means\n**immutable** with a stable hash for the object's lifetime. A tuple of immutable\nvalues is hashable, so it works as a key; a list is mutable and **unhashable**,\nso it doesn't.\n\n```python\ngrid = {}\ngrid[(0, 0)] = \"origin\"   # tuple key — works\ngrid[(1, 2)] = \"point\"\n\ngrid[[3, 4]] = \"x\"        # TypeError: unhashable type: 'list'\n```\n\nThis makes tuples ideal for **composite \u002F multi-part keys** — like `(row, col)`\ncoordinates or `(lat, lon)` pairs. The one caveat: a tuple is only hashable if\n**all its contents are** too, so `(1, [2])` still fails. Use an immutable tuple\nwhenever you need a multi-value key.\n",{"description":61},"Python interview questions on tuples vs lists, packing and unpacking, single-element tuples, shallow immutability, namedtuples, and tuples as dict keys.","python\u002Fdata-structures\u002Ftuples","Tuples & Named Tuples","k8gJCQHd3O516LEW4hNwzbc-dMsxspsIWpQ8XWKiCig",{"id":4499,"title":4500,"body":4501,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4505,"navigation":66,"order":12,"path":4506,"questions":4507,"related":207,"seo":4528,"seoDescription":4529,"stem":4530,"subtopic":4531,"topic":4532,"topicSlug":519,"updated":214,"__hash__":4533},"qa\u002Fpython\u002Fexceptions\u002Fcontext-managers.md","Context Managers",{"type":58,"value":4502,"toc":4503},[],{"title":61,"searchDepth":22,"depth":22,"links":4504},[],{},"\u002Fpython\u002Fexceptions\u002Fcontext-managers",[4508,4512,4516,4520,4524],{"id":4509,"difficulty":71,"q":4510,"a":4511},"what-is-context-manager","What is a context manager and what does the with statement do?","A **context manager** is an object that defines **setup and teardown** logic to run\naround a block of code. The **`with` statement** uses it to guarantee that the\nteardown happens — even if the block raises an exception or returns early — so you\ndon't have to write manual `try\u002Ffinally`.\n\n```python\nwith open(\"data.txt\") as f:   # __enter__ runs, returns the file\n    data = f.read()\n# __exit__ runs here automatically — the file is closed\n```\n\nThe classic use is resource management: files, network sockets, database\nconnections, and locks. Rule of thumb: any \"acquire then must-release\" pattern is\na candidate for a `with` block.\n",{"id":4513,"difficulty":63,"q":4514,"a":4515},"enter-exit","How do __enter__ and __exit__ work?","To make a class a context manager you implement two dunder methods. **`__enter__`**\nruns at the start of the `with` block and its return value is bound to the `as`\nvariable. **`__exit__`** runs when the block ends — always — receiving the\nexception type, value, and traceback (all `None` if the block succeeded).\n\n```python\nclass Timer:\n    def __enter__(self):\n        import time; self.start = time.time()\n        return self                      # bound to 'as t'\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        import time; print(time.time() - self.start)\n        return False                     # don't suppress exceptions\n\nwith Timer() as t:\n    do_work()\n```\n\n`__exit__` always runs, which is what makes cleanup reliable. Rule of thumb:\nacquire the resource in `__enter__`, release it in `__exit__`, and `return self`\nif callers need the object.\n",{"id":4517,"difficulty":63,"q":4518,"a":4519},"contextlib-decorator","How does contextlib.contextmanager simplify writing one?","The **`@contextlib.contextmanager`** decorator lets you write a context manager as a\n**generator** instead of a class. Code **before `yield`** is the setup (`__enter__`),\nthe **yielded value** becomes the `as` target, and code **after `yield`** is the\nteardown (`__exit__`).\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef opened(path):\n    f = open(path)          # setup\n    try:\n        yield f             # value bound to 'as'\n    finally:\n        f.close()           # teardown — runs even on error\n\nwith opened(\"data.txt\") as f:\n    print(f.read())\n```\n\nThe `try\u002Ffinally` around the `yield` is essential — without it the teardown is\nskipped when the block raises. Rule of thumb: reach for the decorator for simple,\none-off managers; write a class when you need state across multiple methods.\n",{"id":4521,"difficulty":84,"q":4522,"a":4523},"exceptions-in-exit","How does a context manager handle exceptions in __exit__?","When the `with` block raises, Python passes the exception details into `__exit__`.\nThe crucial part is the **return value**: returning a **truthy** value tells Python\nto **suppress** the exception, while returning `False`\u002F`None` lets it **propagate**\nnormally.\n\n```python\nclass Suppress:\n    def __enter__(self): return self\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if exc_type is ValueError:\n            print(\"swallowed:\", exc_val)\n            return True          # suppress ValueError\n        return False             # re-raise anything else\n\nwith Suppress():\n    raise ValueError(\"oops\")     # swallowed, program continues\n```\n\n`contextlib.suppress(ValueError)` is the ready-made version of this pattern. Rule\nof thumb: only suppress exceptions you genuinely intend to ignore — accidentally\nreturning a truthy value hides bugs.\n",{"id":4525,"difficulty":71,"q":4526,"a":4527},"multiple-context-managers","How do you use multiple context managers and what are real uses?","You can manage several resources in one `with` by separating them with commas (or\nusing parenthesized form in 3.10+). They are **entered left to right** and\n**exited in reverse order**, so cleanup unwinds correctly.\n\n```python\nwith open(\"in.txt\") as src, open(\"out.txt\", \"w\") as dst:\n    dst.write(src.read())\n# dst closed first, then src\n\nimport threading\nlock = threading.Lock()\nwith lock:                 # acquire on enter, release on exit\n    shared_counter += 1\n```\n\nCommon real uses: **files** (auto-close), **locks** (auto-release even on error),\n**database transactions** (commit\u002Frollback), and temporarily **changing state**\nlike `decimal.localcontext`. Rule of thumb: if you ever write `try\u002Ffinally` to\nrelease something, a context manager expresses it more clearly.\n",{"description":61},"Python interview questions on context managers and the with statement, __enter__\u002F__exit__, contextlib.contextmanager, exception handling in __exit__, and multiple context managers.","python\u002Fexceptions\u002Fcontext-managers","Context Managers & with","Errors & Exceptions","_wYx3YKUE7hQadgYFrkMXwIkQXcyoJFa0Pm0YBK9cu8",{"id":4535,"title":4536,"body":4537,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4541,"navigation":66,"order":31,"path":4542,"questions":4543,"related":207,"seo":4568,"seoDescription":4569,"stem":4570,"subtopic":4571,"topic":4532,"topicSlug":519,"updated":214,"__hash__":4572},"qa\u002Fpython\u002Fexceptions\u002Fcustom-exceptions.md","Custom Exceptions",{"type":58,"value":4538,"toc":4539},[],{"title":61,"searchDepth":22,"depth":22,"links":4540},[],{},"\u002Fpython\u002Fexceptions\u002Fcustom-exceptions",[4544,4548,4552,4556,4560,4564],{"id":4545,"difficulty":63,"q":4546,"a":4547},"hierarchy","What is the Python exception hierarchy and why shouldn't you catch BaseException?","All exceptions inherit from **`BaseException`** at the root. Directly under it sit a\nfew special ones — **`SystemExit`**, **`KeyboardInterrupt`**, and\n**`GeneratorExit`** — that are **not** meant to be caught by normal error handling.\nEverything you'd normally catch (and every built-in error like `ValueError`)\ndescends from **`Exception`**, which is itself a child of `BaseException`.\n\n```python\n# BaseException\n#  ├── SystemExit\n#  ├── KeyboardInterrupt\n#  └── Exception          \u003C- catch THIS, not BaseException\n#       ├── ValueError\n#       ├── KeyError\n#       └── ...\n```\n\nCatching `BaseException` (or a bare `except:`) traps `KeyboardInterrupt` and\n`SystemExit`, so Ctrl-C and clean shutdowns stop working. **Catch `Exception`**\n(or narrower) and let the system-level ones propagate.\n",{"id":4549,"difficulty":71,"q":4550,"a":4551},"defining-custom","How do you define a custom exception class?","Subclass **`Exception`** (almost never `BaseException`). The simplest custom\nexception needs no body at all — `pass` is enough, since it inherits message\nhandling from `Exception`.\n\n```python\nclass ConfigError(Exception):\n    \"\"\"Raised when configuration is invalid.\"\"\"\n\nraise ConfigError(\"missing 'port' key\")\n\ntry:\n    ...\nexcept ConfigError as e:\n    print(e)            # missing 'port' key\n```\n\nGive the class a clear, specific name ending in `Error`, and a docstring describing\nwhen it's raised. Even an empty subclass is valuable because it lets callers catch\n*your* error specifically instead of a generic `Exception`.\n",{"id":4553,"difficulty":63,"q":4554,"a":4555},"when-to-subclass","When and why should you create custom exceptions?","Create a custom exception when callers need to **distinguish your error** from\nothers and handle it differently. A common pattern is a single **base exception for\nyour library\u002Fapp**, with specific subclasses beneath it — so users can catch the\nbase to handle \"anything from this library\" or a subclass for fine-grained control.\n\n```python\nclass PaymentError(Exception):\n    \"\"\"Base for all payment problems.\"\"\"\n\nclass CardDeclined(PaymentError): pass\nclass InsufficientFunds(PaymentError): pass\n\ntry:\n    charge(card)\nexcept InsufficientFunds:\n    retry_later()\nexcept PaymentError:          # catches any other payment error\n    alert_support()\n```\n\nDon't invent a custom exception when a built-in already fits — bad input is a\n`ValueError`, a missing key is a `KeyError`. Add your own only when it carries\nmeaning the built-ins can't.\n",{"id":4557,"difficulty":63,"q":4558,"a":4559},"passing-args","How do you pass arguments and messages to an exception?","Arguments passed to an exception are stored in its **`.args`** tuple, and the first\none becomes the string returned by `str(exception)`. To attach **structured data**,\nadd attributes in a custom `__init__` (and call `super().__init__()` so the message\nstill works).\n\n```python\nraise ValueError(\"bad value\", 42)\n# e.args == (\"bad value\", 42)\n\nclass ApiError(Exception):\n    def __init__(self, message, status_code):\n        super().__init__(message)   # sets the message \u002F .args\n        self.status_code = status_code\n\ntry:\n    raise ApiError(\"not found\", 404)\nexcept ApiError as e:\n    print(e, e.status_code)         # not found 404\n```\n\nUse a plain message for simple cases; add attributes when handlers need to inspect\ndetails (like an HTTP status or the offending value) rather than parse the text.\n",{"id":4561,"difficulty":63,"q":4562,"a":4563},"base-catches-subclasses","Why does catching a base exception class also catch its subclasses?","`except` matches via **`isinstance`**, so a handler for a base class catches the\nbase **and every subclass**. That's why `except Exception` catches almost\neverything, and why ordering matters: put **specific subclasses before** their base,\nor the base will intercept them first.\n\n```python\nclass AppError(Exception): pass\nclass NotFound(AppError): pass\n\ntry:\n    raise NotFound(\"user\")\nexcept AppError:            # matches — NotFound IS-A AppError\n    print(\"caught by base\")\n\ntry:\n    raise NotFound(\"user\")\nexcept AppError:            # this runs first...\n    print(\"base\")\nexcept NotFound:            # ...so this is unreachable!\n    print(\"specific\")\n```\n\nOrder `except` clauses **most-specific first**. The same rule is why\n`except Exception` should come last among your handlers.\n",{"id":4565,"difficulty":71,"q":4566,"a":4567},"common-builtins","What are some common built-in exceptions and when are they raised?","Knowing the standard ones lets you catch precisely and raise the *right* error.\n**`ValueError`** — right type, wrong value (`int(\"abc\")`). **`TypeError`** — wrong\ntype entirely (`\"x\" + 1`). **`KeyError`** — missing dict key. **`IndexError`** —\nlist index out of range. **`AttributeError`** — missing attribute. **`KeyError`**\nand **`IndexError`** both subclass **`LookupError`**.\n\n```python\nint(\"abc\")          # ValueError\n\"x\" + 1             # TypeError\n{\"a\": 1}[\"b\"]       # KeyError\n[1, 2][5]           # IndexError\nNone.foo            # AttributeError\n```\n\nRaise the built-in that best describes the problem instead of a generic\n`Exception` — `ValueError` for bad arguments, `TypeError` for wrong types — so\ncallers can handle them idiomatically.\n",{"description":61},"Python interview questions on the exception hierarchy, BaseException vs Exception, defining custom exception classes, passing messages, and how catching a base class catches its subclasses.","python\u002Fexceptions\u002Fcustom-exceptions","Custom Exceptions & the Hierarchy","_NsIl_DBSx_bgYPk7Jw_vU-Q07dm94XjSeGNaH_9WLM",{"id":4574,"title":4575,"body":4576,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4580,"navigation":66,"order":22,"path":4581,"questions":4582,"related":207,"seo":4603,"seoDescription":4604,"stem":4605,"subtopic":4606,"topic":4532,"topicSlug":519,"updated":214,"__hash__":4607},"qa\u002Fpython\u002Fexceptions\u002Ftry-except.md","Try Except",{"type":58,"value":4577,"toc":4578},[],{"title":61,"searchDepth":22,"depth":22,"links":4579},[],{},"\u002Fpython\u002Fexceptions\u002Ftry-except",[4583,4587,4591,4595,4599],{"id":4584,"difficulty":63,"q":4585,"a":4586},"four-clauses","What do the try, except, else, and finally clauses do and when does each run?","A full statement has four parts. **`try`** holds the code that might fail.\n**`except`** runs only if a matching exception was raised in `try`. **`else`**\nruns only if `try` finished **without** raising — it's for the \"success path\"\ncode you don't want wrapped in the `try`. **`finally`** runs **always**, whether\nthere was an exception or not, and even if you `return`\u002F`break` — it's for cleanup.\n\n```python\ntry:\n    conn = open_db()          # might raise\nexcept DBError as e:\n    log(e)                    # runs only on failure\nelse:\n    conn.commit()             # runs only on success\nfinally:\n    conn.close()              # always runs — cleanup\n```\n\nPutting the success-only code in `else` (instead of at the bottom of `try`) keeps\nthe `try` block narrow, so `except` only catches errors from the risky line.\n",{"id":4588,"difficulty":63,"q":4589,"a":4590},"catch-multiple","How do you catch multiple exception types, and what does `as e` give you?","Group related types in a **tuple** after `except`, or use separate `except`\nclauses when each needs different handling. The `as e` binds the **exception\ninstance**, letting you inspect its message, args, or attributes.\n\n```python\ntry:\n    value = int(raw)\nexcept (ValueError, TypeError) as e:   # tuple -> one handler for both\n    print(f\"bad input: {e}\")           # e is the exception object\nexcept KeyError:                       # separate handler, different logic\n    print(\"missing key\")\n```\n\nClauses are checked **top to bottom**, and the **first match wins** — so order\nspecific exceptions before their base classes. Use the tuple form when several\ntypes share handling; use separate clauses when they don't.\n",{"id":4592,"difficulty":63,"q":4593,"a":4594},"bare-except","Why is a bare `except:` considered bad practice?","A bare `except:` (or `except BaseException:`) catches **everything** — including\n`KeyboardInterrupt` and `SystemExit`, which are how the user Ctrl-Cs or the\nprogram exits. It also **swallows bugs** like `NameError` or `TypeError` that you'd\nrather see crash loudly, making problems invisible.\n\n```python\ntry:\n    do_work()\nexcept:                 # too broad — even Ctrl-C is caught\n    pass                # silent failure — hides real bugs\n\ntry:\n    do_work()\nexcept Exception as e:  # catches errors, not Ctrl-C \u002F SystemExit\n    log.exception(e)    # at least record what happened\n```\n\nCatch the **narrowest** exception you can actually handle. If you must catch\nbroadly, use `except Exception` (not bare), and always log rather than silently\n`pass`.\n",{"id":4596,"difficulty":84,"q":4597,"a":4598},"finally-return","What happens when `finally` contains a `return`?","`finally` always runs, even when `try` or `except` already has a `return`. If\n`finally` itself **returns** (or raises), it **overrides** the pending return or\nexception — the value from `try`\u002F`except` is silently discarded. This is a classic\ngotcha.\n\n```python\ndef f():\n    try:\n        return 1        # value queued...\n    finally:\n        return 2        # ...but finally's return wins\nf()                     # 2, not 1\n\ndef g():\n    try:\n        raise ValueError\n    finally:\n        return \"swallowed\"   # finally return suppresses the exception!\ng()                     # \"swallowed\" — exception vanishes\n```\n\nAvoid `return`\u002F`break` inside `finally`: it masks both return values and\nexceptions. Keep `finally` for cleanup only.\n",{"id":4600,"difficulty":84,"q":4601,"a":4602},"reraise-chaining","How do you re-raise an exception and what is exception chaining?","A bare **`raise`** (no argument) inside an `except` block **re-raises the current\nexception**, preserving its original traceback — useful for logging then letting it\npropagate. To translate one error into another while keeping the cause, use\n**`raise NewError from original`**, which sets `__cause__` and shows both in the\ntraceback.\n\n```python\ntry:\n    parse(config)\nexcept KeyError as e:\n    log.error(\"config invalid\")\n    raise                       # re-raise same exception, original traceback\n\ntry:\n    value = data[\"port\"]\nexcept KeyError as e:\n    raise ConfigError(\"missing port\") from e   # explicit chaining\n```\n\nWhen an exception is raised **inside** an `except` block without `from`, Python\nstill links it implicitly via `__context__` (\"During handling of the above...\"). Use\n`from e` to make the cause explicit, or `from None` to suppress the chain.\n",{"description":61},"Python interview questions on try\u002Fexcept\u002Felse\u002Ffinally, catching multiple exception types, why bare except is bad, finally with return, and exception chaining with raise from.","python\u002Fexceptions\u002Ftry-except","try \u002F except \u002F else \u002F finally","zypRLfxfYjZySj7ZLjRlUt8LzLvDa0sVDs3sO4N7lzk",{"id":4609,"title":4610,"body":4611,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4615,"navigation":66,"order":12,"path":4616,"questions":4617,"related":207,"seo":4638,"seoDescription":4639,"stem":4640,"subtopic":4641,"topic":4642,"topicSlug":4643,"updated":214,"__hash__":4644},"qa\u002Fpython\u002Ffunctional\u002Ffunctools.md","Functools",{"type":58,"value":4612,"toc":4613},[],{"title":61,"searchDepth":22,"depth":22,"links":4614},[],{},"\u002Fpython\u002Ffunctional\u002Ffunctools",[4618,4622,4626,4630,4634],{"id":4619,"difficulty":63,"q":4620,"a":4621},"lru-cache","What does functools.lru_cache do?","**`functools.lru_cache`** is a decorator that **memoizes** a function — it stores\nresults keyed by the arguments and returns the cached value on repeat calls,\navoiding recomputation. `maxsize` caps how many results are kept, evicting the\n**least-recently-used** entries; `lru_cache(maxsize=None)` (or `functools.cache`\nin 3.9+) caches without limit.\n\n```python\nfrom functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fib(n):\n    return n if n \u003C 2 else fib(n - 1) + fib(n - 2)\n\nfib(50)                 # fast — each n computed once\nfib.cache_info()        # hits, misses, maxsize, currsize\nfib.cache_clear()       # reset the cache\n```\n\nArguments must be **hashable** (they're used as dict keys), and the function should\nbe **pure** — caching an impure function returns stale results. Rule of thumb: use\nit for expensive, deterministic calls with repeated inputs.\n",{"id":4623,"difficulty":63,"q":4624,"a":4625},"partial","What is functools.partial used for?","**`functools.partial`** creates a new callable with some arguments of an existing\nfunction **pre-filled**. It's a clean way to specialize a general function without\nwriting a wrapper or a `lambda`.\n\n```python\nfrom functools import partial\n\ndef power(base, exp):\n    return base ** exp\n\nsquare = partial(power, exp=2)   # exp fixed to 2\ncube   = partial(power, exp=3)\n\nsquare(5)    # 25\ncube(2)      # 8\n```\n\nPartials are handy for callbacks, event handlers, and configuring functions passed\nto `map`\u002F`sorted`\u002FGUI bindings. Rule of thumb: reach for `partial` when you keep\ncalling the same function with one or two fixed arguments.\n",{"id":4627,"difficulty":63,"q":4628,"a":4629},"wraps","Why do you use functools.wraps when writing a decorator?","A decorator replaces the original function with a wrapper, which **loses the\noriginal's metadata** — its `__name__`, `__doc__`, and signature now point at the\nwrapper. **`functools.wraps`** copies that metadata from the wrapped function onto\nthe wrapper, so introspection, debugging, and documentation still work.\n\n```python\nfrom functools import wraps\n\ndef log(fn):\n    @wraps(fn)                 # copy fn's metadata to wrapper\n    def wrapper(*args, **kwargs):\n        print(\"calling\", fn.__name__)\n        return fn(*args, **kwargs)\n    return wrapper\n\n@log\ndef greet(): \"say hi\"\ngreet.__name__   # 'greet'  (without @wraps it'd be 'wrapper')\n```\n\nWithout `@wraps`, tools like `help()`, tracebacks, and doc generators show the\nwrapper instead of the real function. Rule of thumb: always add `@wraps(fn)` to the\ninner function of any decorator.\n",{"id":4631,"difficulty":63,"q":4632,"a":4633},"reduce","What does functools.reduce do?","**`functools.reduce`** repeatedly applies a two-argument function across an iterable,\n**folding** it down to a single accumulated value. It carries a running result,\ncombining it with each element in turn; an optional **initializer** seeds the\naccumulator (and makes it safe on empty iterables).\n\n```python\nfrom functools import reduce\n\nreduce(lambda acc, x: acc + x, [1, 2, 3, 4])      # 10\nreduce(lambda acc, x: acc * x, [1, 2, 3, 4], 1)   # 24, seeded with 1\n```\n\nFor common folds Python already has built-ins (`sum`, `max`, `min`, `any`, `all`)\nthat are clearer and faster — `reduce` shines for custom accumulation logic. Rule\nof thumb: prefer a built-in or an explicit loop unless the fold is genuinely\nbespoke, since `reduce` can hurt readability.\n",{"id":4635,"difficulty":84,"q":4636,"a":4637},"cached-property-singledispatch","What are cached_property and singledispatch?","**`functools.cached_property`** turns a method into a property whose result is\n**computed once and stored on the instance**, so later accesses are cheap. The\ncached value lives in the instance `__dict__` and is recomputed only if you delete\nit. **`functools.singledispatch`** creates a **generic function** that dispatches to\ndifferent implementations based on the **type of the first argument** — function\noverloading by type.\n\n```python\nfrom functools import cached_property, singledispatch\n\nclass Dataset:\n    @cached_property\n    def stats(self):           # expensive; runs once per instance\n        return expensive_scan(self.data)\n\n@singledispatch\ndef describe(x): return f\"value: {x}\"\n@describe.register\ndef _(x: list): return f\"list of {len(x)}\"\n@describe.register\ndef _(x: int): return f\"int {x}\"\n\ndescribe([1, 2])   # 'list of 2'\ndescribe(7)        # 'int 7'\n```\n\n`cached_property` trades memory for speed on costly, stable computations;\n`singledispatch` keeps type-specific behaviour in separate, registerable functions\ninstead of a big `if\u002Fisinstance` chain. Rule of thumb: cache derived values that\ndon't change, and dispatch when behaviour varies cleanly by argument type.\n",{"description":61},"Python interview questions on functools — lru_cache and cache, partial, wraps, reduce, cached_property, and singledispatch.","python\u002Ffunctional\u002Ffunctools","functools","Functional Programming","functional","O3Gm_dZN9ODH7b85aBNZuE1Zy-RWDP_xQIzayQMjmcM",{"id":4646,"title":4647,"body":4648,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4652,"navigation":66,"order":31,"path":4653,"questions":4654,"related":207,"seo":4683,"seoDescription":4684,"stem":4685,"subtopic":4686,"topic":4642,"topicSlug":4643,"updated":214,"__hash__":4687},"qa\u002Fpython\u002Ffunctional\u002Fitertools.md","Itertools",{"type":58,"value":4649,"toc":4650},[],{"title":61,"searchDepth":22,"depth":22,"links":4651},[],{},"\u002Fpython\u002Ffunctional\u002Fitertools",[4655,4659,4663,4667,4671,4675,4679],{"id":4656,"difficulty":63,"q":4657,"a":4658},"infinite-iterators","What do count, cycle, and repeat do?","These are the three **infinite iterators**. **`count(start, step)`** yields an\nendless arithmetic sequence. **`cycle(iterable)`** repeats an iterable's items\nforever. **`repeat(value, times)`** yields the same value endlessly, or `times`\ntimes if given.\n\n```python\nfrom itertools import count, cycle, repeat, islice\n\nlist(islice(count(10, 2), 3))      # [10, 12, 14]\nlist(islice(cycle(\"AB\"), 5))       # ['A', 'B', 'A', 'B', 'A']\nlist(repeat(7, 3))                 # [7, 7, 7]\n```\n\nBecause `count` and `cycle` never stop, you must bound them — with `islice`, `zip`,\nor a `break` — or your loop runs forever. They're ideal for generating ids,\nround-robin assignment, or padding.\n",{"id":4660,"difficulty":71,"q":4661,"a":4662},"chain","What does itertools.chain do?","`chain(*iterables)` lazily **concatenates** multiple iterables into one stream,\nwithout building an intermediate combined list. `chain.from_iterable(iter_of_iters)`\ndoes the same when the iterables come from a single iterable (e.g. a list of lists).\n\n```python\nfrom itertools import chain\n\nlist(chain([1, 2], [3, 4], [5]))        # [1, 2, 3, 4, 5]\n\nrows = [[1, 2], [3, 4], [5, 6]]\nlist(chain.from_iterable(rows))         # [1, 2, 3, 4, 5, 6] — flatten one level\n```\n\nIt's the memory-friendly way to iterate over several sequences as if they were one,\nand the idiomatic one-level flatten.\n",{"id":4664,"difficulty":63,"q":4665,"a":4666},"islice","What is islice and how is it different from regular slicing?","`islice(iterable, stop)` or `islice(iterable, start, stop, step)` slices any\n**iterator lazily** — including infinite ones and generators that don't support\n`[ ]` indexing. Unlike list slicing, it **can't use negative indices** (it can't\nlook backward in a stream) and it **consumes** the underlying iterator.\n\n```python\nfrom itertools import islice, count\n\nlist(islice(count(), 2, 7))      # [2, 3, 4, 5, 6] — works on an infinite source\ngen = (x * x for x in range(10))\nlist(islice(gen, 3))             # [0, 1, 4] — slice a generator\n```\n\nUse `islice` to take a window from a stream without materializing it. For a concrete\nlist where you want negative indices, ordinary `seq[a:b]` is fine.\n",{"id":4668,"difficulty":63,"q":4669,"a":4670},"combinatorics","What do combinations, permutations, and product produce?","These generate **combinatorial** results lazily. **`permutations(it, r)`** —\nordered arrangements (order matters). **`combinations(it, r)`** — unordered\nselections (order doesn't, no repeats). **`product(*its)`** — the Cartesian product\n(nested loops), with `repeat=n` for self-products.\n\n```python\nfrom itertools import permutations, combinations, product\n\nlist(permutations([1, 2, 3], 2))   # (1,2)(1,3)(2,1)(2,3)(3,1)(3,2)\nlist(combinations([1, 2, 3], 2))   # (1,2)(1,3)(2,3)\nlist(product([0, 1], repeat=2))    # (0,0)(0,1)(1,0)(1,1)\n```\n\nCounts grow fast (factorial \u002F exponential), so keep `r` and inputs small or consume\nlazily. `product(a, b)` replaces a nested `for` over two sequences.\n",{"id":4672,"difficulty":84,"q":4673,"a":4674},"groupby","Why does itertools.groupby require sorted input?","`groupby` groups **only consecutive** items that share a key — it does **not** sort\nfirst. So the same key appearing in non-adjacent positions creates **multiple\ngroups**. To get one group per key, **sort by the same key function first**.\n\n```python\nfrom itertools import groupby\n\ndata = [\"apple\", \"avocado\", \"banana\", \"apricot\"]\n# WRONG — not sorted: 'a' group splits because 'banana' is between\nfor k, g in groupby(data, key=lambda s: s[0]):\n    print(k, list(g))      # a [...] , b [...] , a [apricot]\n\ndata.sort(key=lambda s: s[0])      # sort by the SAME key\nfor k, g in groupby(data, key=lambda s: s[0]):\n    print(k, list(g))      # a [...], b [...]  — correct\n```\n\nAlso note each group is a **lazy sub-iterator** that's invalidated when you advance\nto the next group — materialize it with `list()` if you need it later. Always sort\nby the grouping key before `groupby`.\n",{"id":4676,"difficulty":63,"q":4677,"a":4678},"accumulate","What does itertools.accumulate do?","`accumulate(iterable, func=operator.add)` yields **running totals** — each output is\nthe function applied cumulatively, so by default you get a running sum. Pass a\ndifferent binary `func` for running max, product, etc.\n\n```python\nfrom itertools import accumulate\nimport operator\n\nlist(accumulate([1, 2, 3, 4]))                 # [1, 3, 6, 10] — running sum\nlist(accumulate([1, 2, 3, 4], operator.mul))   # [1, 2, 6, 24] — running product\nlist(accumulate([3, 1, 4, 1, 5], max))         # [3, 3, 4, 4, 5] — running max\n```\n\nUnlike `functools.reduce`, which returns only the **final** value, `accumulate`\nyields **every intermediate** result lazily. Use it for prefix sums and similar\nscans.\n",{"id":4680,"difficulty":63,"q":4681,"a":4682},"laziness-memory","What is the main benefit of itertools being lazy?","Every `itertools` function returns a **lazy iterator** that computes items **on\ndemand**, so it never holds the whole sequence in memory. This lets you process\n**huge or infinite** streams in **constant memory**, and chain operations into a\npipeline that only does the work actually consumed.\n\n```python\nfrom itertools import count, islice\n\n# find the first 5 squares over 1000 — from an infinite source\nsquares = (n * n for n in count(1))\nbig = (s for s in squares if s > 1000)\nprint(list(islice(big, 5)))    # computed lazily, nothing materialized\n\nsum(islice(count(1), 1_000_000))   # no million-element list built\n```\n\nThe trade-off is that iterators are **single-pass** and not indexable. Reach for\n`itertools` when streaming or composing transformations over large data;\nmaterialize to a list only when you need random access or multiple passes.\n",{"description":61},"Python interview questions on itertools — count\u002Fcycle\u002Frepeat, chain, islice, combinations\u002Fpermutations\u002Fproduct, groupby's sorted-input rule, accumulate, and the memory benefit of lazy iterators.","python\u002Ffunctional\u002Fitertools","itertools","1Gxse2j1ry-O6nBlZJIbeCn668VKgt8dM8TEa8_-mMU",{"id":4689,"title":4690,"body":4691,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4695,"navigation":66,"order":22,"path":4696,"questions":4697,"related":207,"seo":4720,"seoDescription":4721,"stem":4722,"subtopic":4723,"topic":4642,"topicSlug":4643,"updated":214,"__hash__":4724},"qa\u002Fpython\u002Ffunctional\u002Fmap-filter-reduce.md","Map Filter Reduce",{"type":58,"value":4692,"toc":4693},[],{"title":61,"searchDepth":22,"depth":22,"links":4694},[],{},"\u002Fpython\u002Ffunctional\u002Fmap-filter-reduce",[4698,4701,4705,4709,4712,4716],{"id":832,"difficulty":71,"q":4699,"a":4700},"What does map do and is it lazy?","`map(func, iterable)` applies `func` to each item, returning a **lazy iterator** in\nPython 3 — nothing is computed until you iterate it (or wrap it in `list()`). This\nsaves memory on large inputs because results are produced one at a time.\n\n```python\nnums = [1, 2, 3]\nresult = map(lambda x: x * 2, nums)\nprint(result)          # \u003Cmap object ...> — not evaluated yet\nprint(list(result))    # [2, 4, 6] — now it runs\n```\n\nBecause it's lazy, `map` never builds the full result in memory unless you ask for\nit. In Python 2 `map` returned a list — a common gotcha when porting code.\n",{"id":4702,"difficulty":63,"q":4703,"a":4704},"map-multiple-iterables","How does map work with multiple iterables?","Pass several iterables and `map` calls `func` with **one item from each, in\nparallel** — `func` must accept that many arguments. It **stops at the shortest**\niterable, so mismatched lengths simply truncate.\n\n```python\na = [1, 2, 3]\nb = [10, 20, 30]\nlist(map(lambda x, y: x + y, a, b))   # [11, 22, 33]\n\nlist(map(pow, [2, 3, 4], [10, 11]))   # [1024, 177147] — stops at 2 items\n```\n\nThis is handy for element-wise combining without an explicit `zip`. If you need the\n**longest** length (padding the gaps), use `itertools.zip_longest` instead.\n",{"id":4706,"difficulty":71,"q":4707,"a":4708},"filter","What does filter do?","`filter(predicate, iterable)` keeps only the items for which `predicate` returns\ntruthy — also a **lazy iterator** in Python 3. As a special case, passing `None` as\nthe predicate keeps the items that are **truthy themselves**.\n\n```python\nnums = [0, 1, 2, 0, 3]\nlist(filter(lambda x: x > 1, nums))   # [2, 3]\nlist(filter(None, nums))              # [1, 2, 3] — drops falsy values\n```\n\nUse it to drop elements by a condition. For complex conditions, a comprehension\nwith `if` is usually more readable than `filter(lambda ...)`.\n",{"id":4631,"difficulty":63,"q":4710,"a":4711},"What is functools.reduce and why isn't it a built-in anymore?","`functools.reduce(func, iterable, initial)` **folds** an iterable into a single\nvalue by repeatedly applying a two-argument function, carrying an accumulator. In\nPython 3 it was **moved out of the builtins into `functools`** — Guido considered it\nless readable than an explicit loop, so it was demoted to discourage casual use.\n\n```python\nfrom functools import reduce\n\nreduce(lambda acc, x: acc + x, [1, 2, 3, 4], 0)   # 10\n# step by step: 0+1=1, 1+2=3, 3+3=6, 6+4=10\n```\n\nFor common reductions, prefer the dedicated built-ins — `sum`, `max`, `min`,\n`math.prod`, `any`, `all` — which are clearer and faster. Reach for `reduce` only\nwhen no built-in expresses the fold.\n",{"id":4713,"difficulty":63,"q":4714,"a":4715},"vs-comprehensions","When should you use map\u002Ffilter versus a comprehension?","A **list\u002Fgenerator comprehension** is the more Pythonic choice when you'd otherwise\nwrite a `lambda`, because it's more readable and avoids the function-call overhead\nper item. `map`\u002F`filter` shine when you can pass an **existing named function**\n(no lambda) and want a lazy iterator with minimal syntax.\n\n```python\nnums = [1, 2, 3, 4]\n\n[x * 2 for x in nums if x % 2]     # comprehension — clearest with a condition\nlist(map(str, nums))               # map with a built-in — clean, no lambda\nlist(map(lambda x: x * 2, nums))   # lambda makes map less readable\n```\n\nRule of thumb: if it needs a `lambda`, use a comprehension; if you're mapping an\nalready-named function, `map` reads fine. For laziness on huge data, a **generator\nexpression** `(... for ...)` gives both.\n",{"id":4717,"difficulty":63,"q":4718,"a":4719},"consume-once","Why can a map or filter object only be consumed once?","`map`\u002F`filter` (and generators) are **one-shot iterators**: iterating them advances\nan internal position that is never reset. Once exhausted, they yield nothing on a\nsecond pass — a frequent source of \"my second loop is empty\" bugs.\n\n```python\ndoubled = map(lambda x: x * 2, [1, 2, 3])\nlist(doubled)    # [2, 4, 6]\nlist(doubled)    # [] — already consumed!\n\ndoubled = list(map(lambda x: x * 2, [1, 2, 3]))  # materialize once\nsum(doubled); max(doubled)   # reuse freely\n```\n\nIf you need to iterate more than once, **convert to a list** (or other concrete\ncollection) up front. Use the lazy iterator directly only when a single pass is\nenough.\n",{"description":61},"Python interview questions on map laziness and multiple iterables, filter, functools.reduce, map\u002Ffilter vs comprehensions, and consuming lazy iterators only once.","python\u002Ffunctional\u002Fmap-filter-reduce","map, filter & reduce","y6sFK7mPcsPaQc2XKJdXy2VVJ6uRfXj-LWrXBILxPQc",{"id":4726,"title":4727,"body":4728,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4732,"navigation":66,"order":22,"path":4733,"questions":4734,"related":207,"seo":4759,"seoDescription":4760,"stem":4761,"subtopic":4762,"topic":2276,"topicSlug":2277,"updated":214,"__hash__":4763},"qa\u002Fpython\u002Ffunctions\u002Farguments.md","Arguments",{"type":58,"value":4729,"toc":4730},[],{"title":61,"searchDepth":22,"depth":22,"links":4731},[],{},"\u002Fpython\u002Ffunctions\u002Farguments",[4735,4739,4743,4747,4751,4755],{"id":4736,"difficulty":63,"q":4737,"a":4738},"args-kwargs","What do *args and **kwargs do?","In a function signature, **`*args`** collects extra **positional** arguments\ninto a tuple, and **`**kwargs`** collects extra **keyword** arguments into a\ndict. They let a function accept a variable number of arguments. The names\nare convention — only the `*`\u002F`**` matter.\n\n```python\ndef log(level, *args, **kwargs):\n    print(level, args, kwargs)\n\nlog(\"INFO\", 1, 2, user=\"ada\", id=7)\n# INFO (1, 2) {'user': 'ada', 'id': 7}\n```\n\n`args` is always a `tuple` and `kwargs` always a `dict`. They're essential\nfor writing wrappers\u002Fdecorators that forward arbitrary arguments through to\nanother callable.\n",{"id":4740,"difficulty":71,"q":4741,"a":4742},"positional-vs-keyword","What is the difference between positional and keyword arguments?","**Positional arguments** are matched to parameters by their **order**.\n**Keyword arguments** are matched by **name** (`param=value`), so order\ndoesn't matter among them. At the call site you can mix the two, but every\npositional argument must come **before** any keyword argument.\n\n```python\ndef greet(name, greeting): ...\n\ngreet(\"Ada\", \"Hello\")              # both positional\ngreet(name=\"Ada\", greeting=\"Hi\")   # both keyword (order free)\ngreet(\"Ada\", greeting=\"Hi\")        # mix: positional first\ngreet(name=\"Ada\", \"Hi\")            # SyntaxError — kw before positional\n```\n\nKeyword arguments make calls self-documenting and let you skip over earlier\nparameters that have defaults. Use them for clarity on boolean flags and\nlong argument lists.\n",{"id":4744,"difficulty":71,"q":4745,"a":4746},"default-args","How do default argument values work?","A parameter with `name=value` is **optional** — if the caller omits it, the\ndefault is used. Defaults are evaluated **once**, when the `def` runs, so\nusing a **mutable** default (`[]`, `{}`) is a classic trap: the same object\npersists across calls.\n\n```python\ndef connect(host, port=5432, timeout=30):\n    ...\nconnect(\"db\")                 # uses port=5432, timeout=30\nconnect(\"db\", timeout=5)      # override one by keyword\n\ndef bad(item, bucket=[]):     # DON'T — shared list\n    bucket.append(item); return bucket\n```\n\nThe safe pattern for a mutable default is `bucket=None` plus\n`if bucket is None: bucket = []` inside the body. Parameters with defaults\nmust come after those without.\n",{"id":4748,"difficulty":63,"q":4749,"a":4750},"keyword-only","What are keyword-only arguments?","Any parameter listed **after a bare `*`** (or after `*args`) is\n**keyword-only** — it can never be passed positionally and must be named at\nthe call site. This forces clearer calls and prevents accidental\npositional mistakes.\n\n```python\ndef make_request(url, *, timeout=30, verify=True):\n    ...\n\nmake_request(\"http:\u002F\u002Fx\", timeout=5)     # OK\nmake_request(\"http:\u002F\u002Fx\", 5)             # TypeError — timeout is kw-only\n```\n\nKeyword-only parameters are great for optional flags whose meaning isn't\nobvious from position (especially booleans). The lone `*` is just a\nseparator; it doesn't collect anything.\n",{"id":4752,"difficulty":84,"q":4753,"a":4754},"positional-only","What are positional-only parameters?","Parameters listed **before a `\u002F`** in the signature are **positional-only**\n(Python 3.8+) — they cannot be passed by keyword. This is useful for APIs\nwhere the parameter name is an implementation detail you don't want callers\nto depend on.\n\n```python\ndef divide(a, b, \u002F):\n    return a \u002F b\n\ndivide(10, 2)          # OK\ndivide(a=10, b=2)      # TypeError — a, b are positional-only\n```\n\nIt also frees those names for use in `**kwargs`. Many built-ins (like\n`len`, `pow`) are positional-only. Combined with `*`, a signature can have\npositional-only, normal, and keyword-only sections.\n",{"id":4756,"difficulty":63,"q":4757,"a":4758},"param-ordering","What is the correct order of parameters in a signature?","A full signature follows a fixed order:\n**positional-only `\u002F`, then normal, then `*args`, then keyword-only, then\n`**kwargs`**. Within each group, parameters without defaults precede those\nwith defaults.\n\n```python\ndef f(pos_only, \u002F, normal, *args, kw_only, **kwargs):\n    ...\n\n# call-site unpacking mirrors this:\ndef g(a, b, c): ...\nnums = [1, 2, 3]\ng(*nums)                 # spread list into positionals\ng(**{\"a\": 1, \"b\": 2, \"c\": 3})   # spread dict into keywords\n```\n\nGetting the order wrong is a `SyntaxError`. The `*`\u002F`\u002F` markers partition\nthe signature; remember the sequence \"positional-only → normal → varargs →\nkeyword-only → varkwargs.\"\n",{"description":61},"Python interview questions on args and kwargs, positional vs keyword arguments, defaults, keyword-only and positional-only parameters, unpacking at the call site, and parameter ordering rules.","python\u002Ffunctions\u002Farguments","Function Arguments","T4lWvDZqp8gjS6SokbQyTXGimya-uvBG8xPkeyfFJ4k",{"id":4765,"title":2129,"body":4766,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":4770,"navigation":66,"order":31,"path":4771,"questions":4772,"related":207,"seo":4793,"seoDescription":4794,"stem":4795,"subtopic":4796,"topic":2276,"topicSlug":2277,"updated":214,"__hash__":4797},"qa\u002Fpython\u002Ffunctions\u002Fclosures.md",{"type":58,"value":4767,"toc":4768},[],{"title":61,"searchDepth":22,"depth":22,"links":4769},[],{},"\u002Fpython\u002Ffunctions\u002Fclosures",[4773,4777,4781,4785,4789],{"id":4774,"difficulty":84,"q":4775,"a":4776},"what-is-a-closure","What is a closure and what are free variables?","A **closure** is a nested function that **remembers variables from its\nenclosing scope** even after that outer function has returned. The\nremembered names are called **free variables** — they're neither local\nparameters nor globals. Python stores them on the function's `__closure__`\nattribute.\n\n```python\ndef multiplier(factor):\n    def multiply(n):\n        return n * factor      # 'factor' is a free variable\n    return multiply\n\ndouble = multiplier(2)\ndouble(5)                      # 10\ndouble.__closure__[0].cell_contents   # 2 — captured value\n```\n\nThe inner function keeps the binding alive via a **cell object**, which is\nwhy `multiplier` can return and `double` still works. Closures are how\nPython functions carry private state without a class.\n",{"id":4778,"difficulty":63,"q":4779,"a":4780},"nonlocal","What does the nonlocal keyword do?","By default, assigning to a name inside a function creates a **new local**.\n**`nonlocal`** tells Python that an assignment should instead **rebind a\nvariable in the nearest enclosing function scope** — letting a closure\nmutate, not just read, the captured variable.\n\n```python\ndef counter():\n    count = 0\n    def increment():\n        nonlocal count        # rebind outer 'count'\n        count += 1\n        return count\n    return increment\n\nc = counter()\nc(); c()                       # 1, then 2\n```\n\nWithout `nonlocal`, `count += 1` would raise `UnboundLocalError` (it reads\nthen assigns a local). Use `nonlocal` for enclosing-function scope and\n`global` for module scope.\n",{"id":4782,"difficulty":84,"q":4783,"a":4784},"late-binding","Why do closures in a loop all capture the same value?","Closures capture **variables, not values** — this is **late binding**. A\nfunction created in a loop looks up the loop variable when it's *called*, not\nwhen it's defined, so every closure sees the variable's **final** value.\n\n```python\nfuncs = [lambda: i for i in range(3)]\n[f() for f in funcs]           # [2, 2, 2]  — all see final i\n\n# fix: bind the current value via a default argument\nfuncs = [lambda i=i: i for i in range(3)]\n[f() for f in funcs]           # [0, 1, 2]\n```\n\nThe default-argument trick works because **defaults are evaluated at\ndefinition time**, snapshotting `i` per iteration. A factory function that\ntakes `i` as a parameter achieves the same. This is a favorite interview\ngotcha.\n",{"id":4786,"difficulty":84,"q":4787,"a":4788},"closure-cell","How can you inspect a closure's captured variables?","A function with free variables has a non-`None` **`__closure__`** — a tuple\nof **cell** objects, each holding one captured binding accessible via\n`cell_contents`. The matching names are listed in\n`__code__.co_freevars`. Functions with no closure have `__closure__ is\nNone`.\n\n```python\ndef make(x, y):\n    def inner():\n        return x + y\n    return inner\n\nf = make(3, 4)\nf.__code__.co_freevars               # ('x', 'y')\n[c.cell_contents for c in f.__closure__]   # [3, 4]\n```\n\nThis is mostly useful for debugging or teaching how closures actually\nstore state. The cells are shared live, so `nonlocal` rebinds are visible\nthrough `cell_contents`.\n",{"id":4790,"difficulty":63,"q":4791,"a":4792},"closures-vs-classes","When should you use a closure instead of a class?","Both bundle **behavior with state**. A **closure** is lighter and ideal\nwhen you need a *single* method and a little hidden state. A **class** wins\nwhen you need multiple methods, inheritance, or explicit, inspectable\nstate. Common closure uses include **factories, decorators, and callbacks**.\n\n```python\n# closure: tiny stateful function\ndef make_adder(n):\n    return lambda x: x + n\nadd10 = make_adder(10)\n\n# class: equivalent but heavier\nclass Adder:\n    def __init__(self, n): self.n = n\n    def __call__(self, x): return x + self.n\n```\n\nRule of thumb: one behavior + private state → closure; many behaviors or\nshared interface → class. Decorators are the canonical real-world closure.\n",{"description":61},"Python interview questions on closures and free variables, __closure__, the nonlocal keyword, late binding in loops and the default-argument fix, closures vs classes, and common closure uses.","python\u002Ffunctions\u002Fclosures","Closures & Scope","UgESsdHC55Ja_QpbICRE7AnqAyUYkc7CLH5xgyGMyz8",{"id":4799,"title":4800,"body":4801,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":4805,"navigation":66,"order":12,"path":4806,"questions":4807,"related":207,"seo":4828,"seoDescription":4829,"stem":4830,"subtopic":4800,"topic":2276,"topicSlug":2277,"updated":214,"__hash__":4831},"qa\u002Fpython\u002Ffunctions\u002Fdecorators.md","Decorators",{"type":58,"value":4802,"toc":4803},[],{"title":61,"searchDepth":22,"depth":22,"links":4804},[],{},"\u002Fpython\u002Ffunctions\u002Fdecorators",[4808,4812,4816,4820,4824],{"id":4809,"difficulty":63,"q":4810,"a":4811},"what-is-decorator","What is a decorator and how does it work?","A **decorator** is a **callable that takes a function and returns a (usually\nwrapped) function**, letting you add behaviour **without modifying** the original.\nThe `@decorator` syntax above a `def` is just sugar for **reassigning the name** to\nthe decorator's result: `func = decorator(func)`.\n\n```python\ndef log_calls(func):\n    def wrapper(*args, **kwargs):    # accept any signature\n        print(f\"calling {func.__name__}\")\n        return func(*args, **kwargs) # delegate to the original\n    return wrapper\n\n@log_calls\ndef add(a, b):\n    return a + b\n# equivalent to: add = log_calls(add)\n\nadd(2, 3)   # prints \"calling add\", returns 5\n```\n\nThis works because functions are **first-class objects** — they can be passed\naround and returned. Decorators are the idiomatic way to factor out\n**cross-cutting concerns** (logging, timing, caching, access control).\n",{"id":4813,"difficulty":84,"q":4814,"a":4815},"functools-wraps","Why should you use functools.wraps in a decorator?","Without it, the wrapper **replaces the original function's identity**: the\ndecorated object reports the **wrapper's** `__name__`, `__doc__`, signature, and\n`__module__`, which breaks introspection, debugging, and tools that rely on\nmetadata. **`functools.wraps`** copies that metadata from the original onto the\nwrapper.\n\n```python\nimport functools\n\ndef log_calls(func):\n    @functools.wraps(func)       # copy name, docstring, __wrapped__, etc.\n    def wrapper(*args, **kwargs):\n        return func(*args, **kwargs)\n    return wrapper\n\n@log_calls\ndef greet():\n    \"say hello\"\n    ...\n\ngreet.__name__   # \"greet\"  (without wraps -> \"wrapper\")\ngreet.__doc__    # \"say hello\"\n```\n\nIt also sets `__wrapped__`, so `inspect.signature` and unwrapping still work.\nRule of thumb: **always** apply `@functools.wraps(func)` to your wrapper — it's\neffectively free and prevents subtle bugs.\n",{"id":4817,"difficulty":84,"q":4818,"a":4819},"decorator-with-arguments","How do you write a decorator that takes arguments?","You add **another layer of nesting**: an outer function takes the **decorator's\narguments** and returns the actual decorator, which takes the function and returns\nthe wrapper. So `@repeat(3)` first **calls** `repeat(3)` to get a decorator, which\nis then applied to the function.\n\n```python\nimport functools\n\ndef repeat(n):                       # takes the decorator argument\n    def decorator(func):             # takes the function\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            for _ in range(n):\n                result = func(*args, **kwargs)\n            return result\n        return wrapper\n    return decorator\n\n@repeat(3)                           # repeat(3) returns 'decorator'\ndef ping():\n    print(\"pong\")\n```\n\nThe mental model: `@repeat(3)` is `ping = repeat(3)(ping)` — three calls deep.\nRemember the parentheses: `@repeat(3)` (with args) differs from `@repeat` (passing\nthe function directly), and forgetting them is a common bug.\n",{"id":4821,"difficulty":84,"q":4822,"a":4823},"class-based-decorator","How do you implement a decorator as a class?","A class becomes a decorator by being **callable** — define **`__call__`**. The\n`__init__` receives the decorated function; `__call__` runs the wrapping logic on\neach invocation. This is handy when the decorator needs to **hold state** (like a\ncall count) in a clean, attribute-based way.\n\n```python\nimport functools\n\nclass CountCalls:\n    def __init__(self, func):\n        functools.update_wrapper(self, func)  # the class-based wraps\n        self.func = func\n        self.count = 0\n    def __call__(self, *args, **kwargs):\n        self.count += 1\n        print(f\"call #{self.count}\")\n        return self.func(*args, **kwargs)\n\n@CountCalls\ndef hello():\n    print(\"hi\")\n\nhello(); hello()      # \"call #1\" then \"call #2\"\nhello.count           # 2 — state lives on the instance\n```\n\nUse `functools.update_wrapper` (the function-form of `wraps`) to preserve\nmetadata. Class decorators shine for **stateful** decorators; for simple stateless\nones, a nested function with a `nonlocal` closure is usually lighter.\n",{"id":4825,"difficulty":63,"q":4826,"a":4827},"stacking-decorators","When you stack multiple decorators, in what order do they apply?","Decorators apply **bottom-up** (nearest the function first) at **definition\ntime**, but the resulting wrappers **execute top-down** at **call time**. Stacking\nis just nested application: the top decorator wraps the result of the ones below\nit.\n\n```python\n@a\n@b\ndef f(): ...\n# equivalent to: f = a(b(f))   — b wraps first, a wraps outermost\n\ndef bold(fn):\n    return lambda: \"\u003Cb>\" + fn() + \"\u003C\u002Fb>\"\ndef italic(fn):\n    return lambda: \"\u003Ci>\" + fn() + \"\u003C\u002Fi>\"\n\n@bold\n@italic\ndef text():\n    return \"hi\"\n\ntext()   # \"\u003Cb>\u003Ci>hi\u003C\u002Fi>\u003C\u002Fb>\"  — bold is outer, runs around italic\n```\n\nSo the **closest** decorator is applied first but its logic runs **innermost**.\nOrder matters whenever decorators have side effects or transform results — e.g.\nput `@staticmethod` outermost, or `@app.route` above `@login_required` so auth\nruns before the view.\n",{"description":61},"Python interview questions on decorators, functools.wraps, decorators with arguments, class-based decorators, stacking order, and real-world use cases.","python\u002Ffunctions\u002Fdecorators","lkoUwwiWM-viu-zDimboEggNtVDCmWFyyrcd9HEU_xI",{"id":4833,"title":4834,"body":4835,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4839,"navigation":66,"order":40,"path":4840,"questions":4841,"related":207,"seo":4860,"seoDescription":4861,"stem":4862,"subtopic":4863,"topic":2276,"topicSlug":2277,"updated":214,"__hash__":4864},"qa\u002Fpython\u002Ffunctions\u002Flambdas.md","Lambdas",{"type":58,"value":4836,"toc":4837},[],{"title":61,"searchDepth":22,"depth":22,"links":4838},[],{},"\u002Fpython\u002Ffunctions\u002Flambdas",[4842,4846,4850,4853,4857],{"id":4843,"difficulty":71,"q":4844,"a":4845},"lambda-syntax","What is a lambda and what are its limitations?","A **lambda** is an anonymous, single-**expression** function:\n`lambda args: expression`. It returns the expression's value automatically\n(no `return`). Its limitation is exactly that — it can hold only **one\nexpression**, no statements, assignments, loops, or annotations.\n\n```python\nsquare = lambda x: x * x\nsquare(5)                  # 25\n\nadd = lambda a, b=1: a + b # defaults allowed\nadd(10)                    # 11\n\n# NOT allowed: lambda x: (y = x; return y)  — no statements\n```\n\nBecause it's an expression, a lambda can be passed inline wherever a\nfunction is expected. Keep them short; anything needing multiple lines or a\ndocstring should be a named `def`.\n",{"id":4847,"difficulty":63,"q":4848,"a":4849},"lambda-vs-def","When should you use a lambda versus a def?","Use a **lambda** for a tiny throwaway function passed **inline** as an\nargument (a sort key, a callback). Use **`def`** for anything reused, named,\ndocumented, or non-trivial. A named function gives a useful `__name__` in\ntracebacks; a lambda just shows `\u003Clambda>`.\n\n```python\n# good lambda: inline, one-off\nsorted(words, key=lambda w: len(w))\n\n# prefer def: reused \u002F needs a name\ndef by_length(w):\n    return len(w)\n```\n\nPEP 8 even discourages **assigning** a lambda to a name\n(`f = lambda x: ...`) — if you need a name, just use `def`. Lambdas shine as\narguments, not as definitions.\n",{"id":4851,"difficulty":63,"q":2560,"a":4852},"higher-order-functions","A **higher-order function** is one that **takes a function as an argument\nand\u002For returns a function**. They enable composing and parameterizing\nbehavior. Built-in examples include `map`, `filter`, `sorted`, and the\n`functools` tools.\n\n```python\ndef apply_twice(fn, x):\n    return fn(fn(x))           # takes a function\n\napply_twice(lambda n: n + 3, 10)   # 16\n\nlist(map(str.upper, [\"a\", \"b\"]))   # ['A', 'B']\nlist(filter(lambda n: n > 0, [-1, 2, -3, 4]))  # [2, 4]\n```\n\nHigher-order functions are the foundation of functional-style Python and of\ndecorators (which both take and return functions). They let you pass\n*behavior* around as data.\n",{"id":4854,"difficulty":63,"q":4855,"a":4856},"key-argument","How does the key argument work in sorted, max, and min?","`key` takes a **function** applied to each element to derive the value used\nfor **comparison** — the elements themselves aren't changed, only how\nthey're ranked. It's used by `sorted`, `list.sort`, `max`, and `min`.\n\n```python\nwords = [\"banana\", \"kiwi\", \"apple\"]\n\nsorted(words, key=len)                 # ['kiwi', 'apple', 'banana']\nmax(words, key=len)                    # 'banana'\nsorted(words, key=str.lower)           # case-insensitive\n\npeople = [(\"ada\", 36), (\"grace\", 45)]\nmax(people, key=lambda p: p[1])        # ('grace', 45)\n```\n\n`key` is called **once per element** (efficient), unlike the old `cmp`\nstyle. For multi-level sorts, return a **tuple**:\n`key=lambda p: (p.last, p.first)`.\n",{"id":2306,"difficulty":63,"q":4858,"a":4859},"What does it mean that functions are first-class objects?","In Python, functions are **first-class objects**: they can be assigned to\nvariables, stored in data structures, passed as arguments, and **returned**\nfrom other functions — just like any value. This is what makes higher-order\nfunctions and closures possible.\n\n```python\ndef shout(s): return s.upper() + \"!\"\n\nf = shout                 # assign to a variable\nf(\"hi\")                   # 'HI!'\n\ndispatch = {\"loud\": shout}        # store in a dict\ndispatch[\"loud\"](\"hey\")           # 'HEY!'\n\ndef make_op(op):                  # return a function\n    return (lambda a, b: a + b) if op == \"+\" else (lambda a, b: a - b)\nmake_op(\"+\")(2, 3)                # 5\n```\n\nTreating functions as values enables strategy\u002Fdispatch tables, callbacks,\nand decorators. There's no separate \"function pointer\" concept — the\nfunction *is* the object.\n",{"description":61},"Python interview questions on lambda syntax and limitations, lambda vs def, higher-order functions, the key argument in sorted\u002Fmax\u002Fmin, and functions as first-class objects.","python\u002Ffunctions\u002Flambdas","Lambdas & Higher-Order Functions","9_y3LjVbDK5c4cIpcmC5IQFqaQxIZJqZxiPop420_2E",{"id":4866,"title":4867,"body":4868,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":4872,"navigation":66,"order":12,"path":4873,"questions":4874,"related":207,"seo":5004,"seoDescription":5005,"stem":5006,"subtopic":5007,"topic":667,"topicSlug":668,"updated":1525,"__hash__":5008},"qa\u002Fpython\u002Ffundamentals\u002Fmutability.md","Mutability",{"type":58,"value":4869,"toc":4870},[],{"title":61,"searchDepth":22,"depth":22,"links":4871},[],{},"\u002Fpython\u002Ffundamentals\u002Fmutability",[4875,4879,4883,4887,4891,4895,4899,4903,4907,4911,4915,4919,4923,4927,4931,4935,4939,4943,4946,4950,4954,4958,4962,4966,4969,4973,4977,4981,4985,4989,4993,4997,5000],{"id":4876,"difficulty":71,"q":4877,"a":4878},"mutable-immutable","Which Python types are mutable and which are immutable?","**Immutable** (the value can never change in place — any \"change\" makes a new\nobject): `int`, `float`, `complex`, `bool`, `str`, `tuple`, `frozenset`,\n`bytes`, and `None`.\n\n**Mutable** (can be modified in place): `list`, `dict`, `set`, `bytearray`,\nand most custom class instances.\n\n```python\ns = \"hello\"\nprint(id(s))\ns += \" world\"        # looks like mutation...\nprint(id(s))         # ...but id() changed — a NEW string was created\n\nnums = [1, 2, 3]\nprint(id(nums))\nnums.append(4)       # genuine in-place mutation\nprint(id(nums))      # same id — same object\n```\n\nWhy it matters: mutability drives how **assignment, function arguments, and\n`==`\u002F`is` behave**. Immutable objects are also **hashable** (usable as dict\nkeys \u002F set members), while mutable ones generally aren't.\n",{"id":4880,"difficulty":84,"q":4881,"a":4882},"default-arg","What is the mutable default argument trap?","A function's default argument is **evaluated once, when the `def` statement\nruns** — not on each call. So a mutable default (like `[]` or `{}`) is created\na single time and **shared across every call**, accumulating state between\ninvocations.\n\n```python\ndef add(item, bucket=[]):   # the same list object on every call\n    bucket.append(item)\n    return bucket\n\nadd(1)   # [1]\nadd(2)   # [1, 2]  \u003C- surprise! the list persisted\nadd(3)   # [1, 2, 3]\n```\n\nThe fix is the standard `None` sentinel — use `None` as the default and create\na fresh object inside the body:\n\n```python\ndef add(item, bucket=None):\n    if bucket is None:      # new list per call\n        bucket = []\n    bucket.append(item)\n    return bucket\n```\n",{"id":4884,"difficulty":63,"q":4885,"a":4886},"is-vs-eq","What is the difference between `is` and `==`?","`==` tests **value equality** — \"do these represent the same data?\" — by\ncalling the object's `__eq__`. `is` tests **identity** — \"are these the *exact\nsame object* in memory?\" — comparing `id()`s. They often agree, but not always.\n\n```python\na = [1, 2, 3]\nb = [1, 2, 3]\na == b   # True  — equal contents\na is b   # False — two distinct list objects\n\nc = a\nc is a   # True  — same object\n```\n\n**Rule: use `is` only for singletons** — `None`, `True`, `False` (e.g.\n`if x is None:`). Don't use `is` for numbers or strings: small ints and some\nstrings *appear* to work because CPython caches\u002Finterns them\n(`256 is 256` -> `True`, but `1000 is 1000` can be `False`), which is an\nimplementation detail you shouldn't rely on.\n",{"id":4888,"difficulty":63,"q":4889,"a":4890},"shallow-deep-copy","What is the difference between a shallow and a deep copy?","A **shallow copy** (`copy.copy`, `list(x)`, `x[:]`, `dict(x)`) creates a new\nouter container but **copies references** to the nested objects — so the inner\nobjects are still **shared**. A **deep copy** (`copy.deepcopy`) recursively\ncopies everything, producing a fully **independent** structure.\n\n```python\nimport copy\noriginal = [[1, 2], [3, 4]]\n\nshallow = copy.copy(original)\nshallow[0].append(99)\nprint(original)   # [[1, 2, 99], [3, 4]]  \u003C- inner list was shared!\n\ndeep = copy.deepcopy(original)\ndeep[0].append(99)\nprint(original)   # unchanged — fully independent\n```\n\nUse a shallow copy when the elements are immutable (or sharing is fine); reach\nfor `deepcopy` when you have nested mutable structures and need true isolation\n(note it's slower and handles cycles).\n",{"id":4892,"difficulty":63,"q":4893,"a":4894},"tuple-mutable","Can a tuple contain mutable objects?","Yes. A tuple's **immutability is shallow**: you can't reassign or resize its\nslots, but each slot is just a reference, and if that reference points to a\nmutable object, that object can still be changed in place.\n\n```python\nt = (1, [2, 3])\nt[1].append(4)     # allowed — mutating the list inside\nprint(t)           # (1, [2, 3, 4])\n\nt[1] = [9]         # TypeError — can't reassign a tuple slot\n```\n\nA consequence interviewers love: a tuple containing a list is **not\nhashable**, because hashability requires all contents to be immutable — so\n`hash((1, [2]))` raises `TypeError`, and such a tuple can't be a dict key.\n",{"id":4896,"difficulty":84,"q":4897,"a":4898},"hashable","Why can't you use a list as a dictionary key?","Dictionary keys (and set members) must be **hashable**. Hashing requires that an\nobject's hash value **stays constant for its lifetime**, which in practice means\nit must be **immutable**. Lists are mutable, so Python deliberately makes them\n**unhashable** — they have no `__hash__`.\n\n```python\nd = {}\nd[[1, 2]] = 'x'   # TypeError: unhashable type: 'list'\nd[(1, 2)] = 'x'   # tuples are immutable -> hashable\n```\n\nThe reason is correctness: a dict places a key in a bucket based on its hash. If\na key could mutate after insertion, its hash would change and you'd never be\nable to find it again. Use an immutable equivalent — a **tuple** instead of a\nlist, a `frozenset` instead of a set.\n",{"id":4900,"difficulty":63,"q":4901,"a":4902},"id-function","What does the id() function tell you?","`id(obj)` returns a unique integer **identity** for an object — in CPython, its\nmemory address. Two names with the same `id` refer to the **same object**; `is`\nis essentially an `id` comparison.\n\n```python\na = [1, 2]\nb = a\nid(a) == id(b)   # True  — same object\na is b           # True\nc = [1, 2]\nid(a) == id(c)   # False — equal value, different object\n```\n\n`id` is useful for understanding aliasing and why mutation through one name is\nvisible through another. The actual value is implementation-specific (don't rely\non it being an address).\n",{"id":4904,"difficulty":84,"q":4905,"a":4906},"small-int-cache","Why does `is` sometimes work for equal integers?","CPython **pre-caches small integers** from **−5 to 256** as singletons, so equal\nvalues in that range share one object and `is` returns `True`. Outside that range,\nequal integers are usually distinct objects.\n\n```python\na = 256\nb = 256\na is b      # True  — cached\n\nc = 257\nd = 257\nc is d      # False — separate objects (in a REPL)\nc == d      # True  — always compare values with ==\n```\n\nThis is a CPython implementation detail, **not** a language guarantee. Never use\n`is` to compare numbers — use `==`. `is` is only for singletons like `None`.\n",{"id":4908,"difficulty":84,"q":4909,"a":4910},"string-interning","What is string interning in Python?","CPython **interns** some strings — storing one shared copy — so identical\nstring literals can be the same object. Short, identifier-like strings are\ninterned automatically; others may not be.\n\n```python\na = \"hello\"\nb = \"hello\"\na is b           # True  — interned literal\n\nc = \"hello world!\"\nd = \"hello world!\"\nc is d           # often False (not auto-interned)\n\nimport sys\ne = sys.intern(\"hello world!\")  # force interning\n```\n\nLike int caching, this is an optimization detail. Always compare string **values**\nwith `==`, not identity with `is`.\n",{"id":4912,"difficulty":84,"q":4913,"a":4914},"augmented-tuple","What happens when you use += on a list inside a tuple?","You get a surprising result: the list **is** mutated, **and** a `TypeError` is\nraised. `t[0] += [3]` does `t[0] = t[0] + [3]` — the `+=` extends the list in place\n(succeeds), then tries to reassign the tuple slot (fails, since tuples are\nimmutable).\n\n```python\nt = ([1, 2], 'x')\nt[0] += [3]      # TypeError: 'tuple' object does not support item assignment\nprint(t)         # ([1, 2, 3], 'x')  — the list WAS extended!\n```\n\nSo the mutation happens before the assignment error. Use `t[0].extend([3])` if you\nwant to mutate the inner list without the confusing error.\n",{"id":4916,"difficulty":63,"q":4917,"a":4918},"list-slicing-copy","Does slicing a list create a copy?","Yes — slicing produces a **new (shallow) list** containing the same element\nreferences. `lst[:]` is a common idiom for a shallow copy. But the **elements**\nthemselves are shared, so nested mutables are still linked.\n\n```python\na = [1, 2, 3]\nb = a[:]          # shallow copy\nb.append(4)\na                 # [1, 2, 3] — unaffected\n\nnested = [[1], [2]]\ncopy = nested[:]\ncopy[0].append(9)\nnested            # [[1, 9], [2]] — inner list shared\n```\n\nSlicing copies the outer list only; use `copy.deepcopy` for full independence of\nnested structures.\n",{"id":4920,"difficulty":84,"q":4921,"a":4922},"pass-by-object","Is Python pass-by-value or pass-by-reference?","Neither exactly — Python is **pass-by-object-reference** (a.k.a. \"pass by\nassignment\"). The function receives a reference to the same object, so it can\n**mutate** a mutable argument in place, but **rebinding** the parameter doesn't\naffect the caller.\n\n```python\ndef mutate(lst): lst.append(4)     # caller sees this\ndef rebind(lst): lst = [0]         # caller does NOT see this\n\ndata = [1, 2, 3]\nmutate(data); print(data)  # [1, 2, 3, 4]\nrebind(data); print(data)  # [1, 2, 3, 4] (unchanged)\n```\n\nImmutable args (ints, strings, tuples) can't be mutated, so they *appear*\npass-by-value. The key is mutate-in-place vs reassign-the-name.\n",{"id":4924,"difficulty":84,"q":4925,"a":4926},"deepcopy-cycles","How does deepcopy handle circular references?","`copy.deepcopy` tracks already-copied objects in a **memo dictionary**, so it\nhandles **circular references** without infinite recursion — each object is copied\nonce and reused.\n\n```python\nimport copy\na = [1, 2]\na.append(a)            # a contains itself\nb = copy.deepcopy(a)   # works — no infinite loop\nb[2] is b              # True — the cycle is preserved in the copy\n```\n\nA naive recursive copy would loop forever; `deepcopy`'s memo makes it safe. You\ncan customize copying via `__deepcopy__`\u002F`__copy__` methods on your classes.\n",{"id":4928,"difficulty":63,"q":4929,"a":4930},"is-pitfall","When is using `is` instead of `==` a bug?","Using `is` to compare **values** is a bug — it tests identity, which only\ncoincidentally matches for cached singletons (small ints, interned strings,\n`None`). It fails unpredictably for other values.\n\n```python\nx = 1000\nx is 1000        # may be False (and raises a SyntaxWarning in 3.8+)\nx == 1000        # True\n\na = \"long string value\"\na is \"long string value\"  # often False\n```\n\nRule: use `==` for value equality; reserve `is` for `None`, `True`, `False`, and\nsentinel objects. Linters flag `is` comparisons with literals.\n",{"id":4932,"difficulty":84,"q":4933,"a":4934},"custom-hashable","How do you make a custom class hashable?","Implement both `__eq__` and `__hash__`, keeping them **consistent**: equal objects\nmust have equal hashes. Base the hash on the same immutable fields used for\nequality.\n\n```python\nclass Point:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __eq__(self, other):\n        return (self.x, self.y) == (other.x, other.y)\n    def __hash__(self):\n        return hash((self.x, self.y))\n\n{Point(1, 2), Point(1, 2)}   # one element — treated as equal\n```\n\nDefining `__eq__` **without** `__hash__` makes the class **unhashable** (Python\nsets `__hash__ = None`). Only hash on fields that don't change after creation.\n",{"id":4936,"difficulty":63,"q":4937,"a":4938},"frozen-dataclass","What is a frozen dataclass?","A `@dataclass(frozen=True)` makes instances **immutable** — attempting to set an\nattribute raises `FrozenInstanceError`. Frozen dataclasses also get a `__hash__`\nautomatically, so they're usable as dict keys \u002F set members.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Point:\n    x: int\n    y: int\n\np = Point(1, 2)\np.x = 9          # FrozenInstanceError\n{p: \"origin\"}    # hashable\n```\n\nIt's the concise modern way to define immutable value objects with auto-generated\n`__init__`, `__eq__`, `__repr__`, and `__hash__`.\n",{"id":4940,"difficulty":71,"q":4941,"a":4942},"string-immutability","Why are strings immutable in Python?","Once created, a `str` can't be changed — any \"modification\" returns a **new**\nstring. Immutability enables interning, safe use as dict keys (cached hash), thread\nsafety, and predictable behavior.\n\n```python\ns = \"hello\"\ns[0] = \"H\"           # TypeError: 'str' does not support item assignment\ns = s.replace(\"h\", \"H\")  # new string, rebind\ns += \" world\"        # new string each time\n```\n\nRepeated concatenation in a loop creates many throwaway strings — prefer\n`\"\".join(parts)` for efficiency, the Python analog of `StringBuilder`.\n",{"id":4474,"difficulty":63,"q":4944,"a":4945},"What is the difference between a tuple and a list?","- **`list`** — mutable, variable-length, for **homogeneous, changing** sequences.\n- **`tuple`** — immutable, fixed, for **heterogeneous, fixed records** (and\n  hashable, so usable as dict keys).\n\n```python\npoint = (3, 4)        # fixed record — tuple\nscores = [90, 85]     # changing collection — list\nscores.append(70)     #\npoint[0] = 9          # tuples are immutable\n\nd = {(0, 0): \"origin\"}  # tuple key ; list key would fail\n```\n\nTuples are slightly faster and more memory-efficient, and signal \"this shouldn't\nchange.\" Use a list when you need to add\u002Fremove\u002Freorder.\n",{"id":4947,"difficulty":84,"q":4948,"a":4949},"mutate-during-iteration","What happens if you modify a list while iterating over it?","Modifying a list's size during iteration **skips or repeats elements** because the\ninternal index shifts under you — a classic bug (Python doesn't always raise, it\nsilently misbehaves; dicts\u002Fsets *do* raise `RuntimeError`).\n\n```python\nnums = [1, 2, 3, 4]\nfor n in nums:\n    if n % 2 == 0:\n        nums.remove(n)   # skips elements\nprint(nums)              # [1, 3] sometimes wrong for other inputs\n\nnums = [n for n in nums if n % 2]      # build a new list\n```\n\nIterate over a **copy** (`for n in nums[:]`) or, better, build a new list with a\ncomprehension\u002F`filter`.\n",{"id":4951,"difficulty":63,"q":4952,"a":4953},"del-statement","What does the del statement do?","`del` **unbinds a name** (or removes an item\u002Fslice\u002Fattribute) — it doesn't directly\n\"delete\" the object. The object is garbage-collected only when its **reference\ncount hits zero**.\n\n```python\na = [1, 2, 3]\nb = a\ndel a            # unbinds 'a'; the list still lives (b references it)\nprint(b)         # [1, 2, 3]\n\ndel b[0]         # removes an item -> [2, 3]\n```\n\nSo `del a` removes the *name*, not necessarily the value. For container items it\nmutates the container. After `del a`, referencing `a` raises `NameError`.\n",{"id":4955,"difficulty":63,"q":4956,"a":4957},"rebind-vs-mutate","What is the difference between rebinding and mutating?","**Rebinding** points a name at a **new** object (`x = [...]`); it doesn't affect\nother names pointing at the old object. **Mutating** changes an object **in\nplace** (`x.append(...)`); all names referencing it see the change.\n\n```python\na = [1, 2]\nb = a\na.append(3)   # mutate -> b sees it; b == [1, 2, 3]\na = [9]       # rebind -> b unchanged; b == [1, 2, 3]\n```\n\nThis distinction explains most \"why did my other variable change?\" confusion.\nAliases share mutations but not rebinding.\n",{"id":4959,"difficulty":84,"q":4960,"a":4961},"class-mutable-attr","Why is a mutable class attribute shared across instances?","A mutable value assigned at **class level** (not in `__init__`) is **one object\nshared by every instance**. Mutating it through one instance affects all of them —\na common bug.\n\n```python\nclass Cart:\n    items = []          # shared by ALL instances\n    def add(self, x): self.items.append(x)\n\na, b = Cart(), Cart()\na.add(\"apple\")\nb.items                 # ['apple'] — leaked into b!\n\nclass Cart:\n    def __init__(self):\n        self.items = []  # per-instance\n```\n\nInitialize mutable attributes in `__init__` so each instance gets its own.\n",{"id":4963,"difficulty":84,"q":4964,"a":4965},"list-mult-trap","What is the trap with [[]] * 3?","List multiplication copies the **references**, not the objects — so `[[]] * 3`\ncreates three references to the **same** inner list. Mutating one mutates all.\n\n```python\ngrid = [[]] * 3\ngrid[0].append(1)\nprint(grid)          # [[1], [1], [1]] — all share one list!\n\ngrid = [[] for _ in range(3)]  # three distinct lists\ngrid[0].append(1)\nprint(grid)          # [[1], [], []]\n```\n\nThe same applies to `[0] * 3` (fine for immutable ints) vs `[[]] * 3` (broken for\nmutables). Use a comprehension to get independent inner objects.\n",{"id":4486,"difficulty":63,"q":4967,"a":4968},"What is a namedtuple and when do you use it?","`collections.namedtuple` (or `typing.NamedTuple`) creates an **immutable**\ntuple subclass with **named fields** — readable, hashable, lightweight records.\n\n```python\nfrom collections import namedtuple\nPoint = namedtuple(\"Point\", [\"x\", \"y\"])\np = Point(3, 4)\np.x          # 3  — named access\np[0]         # 3  — still index-accessible\np.x = 9      # immutable\n```\n\nIt's great for returning multiple values with clear names while keeping tuple\nsemantics. For more features (defaults, methods, mutability options), a\n`@dataclass` is the modern alternative.\n",{"id":4970,"difficulty":84,"q":4971,"a":4972},"global-nonlocal","What do the global and nonlocal keywords do?","They let you **rebind** a name from an outer scope. `global` targets module-level\nnames; `nonlocal` targets the nearest enclosing function scope. Without them,\nassignment inside a function creates a **new local** instead.\n\n```python\ncount = 0\ndef inc():\n    global count\n    count += 1        # rebinds the module-level count\n\ndef outer():\n    x = 1\n    def inner():\n        nonlocal x\n        x = 2          # rebinds outer's x\n    inner()\n    return x           # 2\n```\n\nNote you only need them to **reassign** — you can *mutate* an outer mutable object\n(e.g. `list.append`) without `global`\u002F`nonlocal`.\n",{"id":4974,"difficulty":71,"q":4975,"a":4976},"copy-methods","What are the ways to copy a list or dict?","Several produce a **shallow** copy; `copy.deepcopy` is the only deep one.\n\n```python\na = [1, 2, 3]\na[:]            # slice copy\na.copy()        # method\nlist(a)         # constructor\n\nd = {\"x\": 1}\nd.copy()        # method\ndict(d)         # constructor\n{**d}           # unpacking\n\nimport copy\ncopy.deepcopy(a)  # deep — independent nested objects\n```\n\nAll the shallow methods share nested mutable elements; choose `deepcopy` when you\nneed full independence (at a performance cost).\n",{"id":4978,"difficulty":71,"q":4979,"a":4980},"none-identity","Why check for None with `is` rather than ==?","`None` is a **singleton** — there's exactly one `None` object — so `is None` is the\ncorrect, fast, and idiomatic identity check. `== None` can be **overridden** by a\ncustom `__eq__`, giving wrong or surprising results.\n\n```python\nif x is None:        # idiomatic, can't be fooled\n    ...\n\nclass Weird:\n    def __eq__(self, other): return True\nWeird() == None      # True  misleading\nWeird() is None      # False\n```\n\nPEP 8 explicitly recommends `is`\u002F`is not` for `None` comparisons.\n",{"id":4982,"difficulty":63,"q":4983,"a":4984},"set-hashable-elements","Why must set elements be hashable?","Like dict keys, set members are stored by **hash** for O(1) membership tests, so\nthey must be **hashable** (and thus effectively immutable). Lists, dicts, and sets\ncan't be set elements; tuples and frozensets can.\n\n```python\n{1, 2, 3}            #\n{[1], [2]}           # TypeError: unhashable type: 'list'\n{(1, 2), (3, 4)}     # tuples are hashable\n{frozenset({1, 2})}  #\n```\n\nIf you need a set of sets, use `frozenset` for the inner ones. The hashability\nrequirement is the same reason lists can't be dict keys.\n",{"id":4986,"difficulty":63,"q":4987,"a":4988},"comprehension-scope","Do comprehensions leak their loop variable?","In **Python 3**, comprehensions have their **own scope**, so the loop variable does\n**not** leak into the surrounding scope (unlike a regular `for` loop, and unlike\nPython 2).\n\n```python\nsquares = [i * i for i in range(5)]\nprint(i)        # NameError — i is local to the comprehension\n\nfor j in range(5):\n    pass\nprint(j)        # 4 — a normal for loop DOES leak\n```\n\nThis avoids accidental variable clobbering. The same isolation applies to set,\ndict, and generator comprehensions.\n",{"id":4990,"difficulty":71,"q":4991,"a":4992},"tuple-unpacking-swap","How does tuple unpacking enable swapping variables?","Python evaluates the **right side first** into a tuple, then unpacks it into the\nleft-side names — so you can swap without a temporary variable.\n\n```python\na, b = 1, 2\na, b = b, a        # builds (2, 1), then unpacks -> a=2, b=1\n\n# also works for multiple\u002Fextended unpacking:\nfirst, *rest = [1, 2, 3, 4]   # first=1, rest=[2, 3, 4]\n```\n\nThe right-hand tuple is fully created before any assignment, which is why the swap\nis atomic and needs no temp. This is immutability of the intermediate tuple at\nwork.\n",{"id":4994,"difficulty":63,"q":4995,"a":4996},"shallow-nested-trap","What is the trap with shallow-copying nested structures?","A shallow copy duplicates the outer container but **shares the nested objects**, so\nmutating a nested element changes both the original and the copy — a subtle\naliasing bug.\n\n```python\nimport copy\noriginal = {\"users\": [\"ada\"]}\nshallow = copy.copy(original)\nshallow[\"users\"].append(\"grace\")\noriginal[\"users\"]    # ['ada', 'grace'] — shared nested list!\n\ndeep = copy.deepcopy(original)\ndeep[\"users\"].append(\"hopper\")\noriginal[\"users\"]    # unchanged\n```\n\nUse `deepcopy` whenever you copy a structure with nested mutables you intend to\nmodify independently.\n",{"id":4451,"difficulty":63,"q":4998,"a":4999},"What is a frozenset?","A `frozenset` is an **immutable** version of `set` — same operations\n(union, intersection, membership) but no `add`\u002F`remove`. Because it's immutable,\nit's **hashable**, so it can be a dict key or an element of another set.\n\n```python\nfs = frozenset([1, 2, 3])\nfs.add(4)              # AttributeError — immutable\n{fs: \"a set\"}          # hashable key\n{frozenset({1}), frozenset({2})}  # set of sets\n```\n\nUse it for constant sets and whenever you need a set-like value that must be\nhashable.\n",{"id":5001,"difficulty":84,"q":5002,"a":5003},"eq-hash-contract","What is the relationship between __eq__ and __hash__?","They must stay **consistent**: if `a == b`, then `hash(a) == hash(b)`. Otherwise\nhash-based containers (dict, set) misbehave — an object you stored becomes\nunfindable.\n\n```python\nclass Money:\n    def __init__(self, cents): self.cents = cents\n    def __eq__(self, o): return self.cents == o.cents\n    # defined __eq__ but not __hash__ -> unhashable\n{Money(100)}   # TypeError: unhashable type: 'Money'\n```\n\nDefining `__eq__` sets `__hash__` to `None` automatically (making instances\nunhashable) unless you also define `__hash__`. Hash only on fields that never\nchange after creation, or make the object immutable.\n",{"description":61},"Python interview questions on mutable vs immutable types, the mutable default argument trap, is vs ==, and shallow vs deep copy.","python\u002Ffundamentals\u002Fmutability","Mutability & Data Types","lfA_zY1n_f1sWG-yTVHSPtktZt0M8Eoy085LnkCD_To",{"id":5010,"title":5011,"body":5012,"description":61,"difficulty":71,"extension":64,"framework":30,"frameworkSlug":28,"meta":5016,"navigation":66,"order":31,"path":5017,"questions":5018,"related":207,"seo":5043,"seoDescription":5044,"stem":5045,"subtopic":5046,"topic":667,"topicSlug":668,"updated":214,"__hash__":5047},"qa\u002Fpython\u002Ffundamentals\u002Fnumbers-operators.md","Numbers Operators",{"type":58,"value":5013,"toc":5014},[],{"title":61,"searchDepth":22,"depth":22,"links":5015},[],{},"\u002Fpython\u002Ffundamentals\u002Fnumbers-operators",[5019,5023,5027,5031,5035,5039],{"id":5020,"difficulty":71,"q":5021,"a":5022},"numeric-types","What are Python's built-in numeric types?","Three: **`int`** (whole numbers, unlimited size), **`float`** (double-precision\nbinary floating point), and **`complex`** (a real + imaginary part written with\n`j`). `bool` is technically a subclass of `int` (`True == 1`).\n\n```python\na = 42          # int\nb = 3.14        # float\nc = 2 + 3j      # complex\nc.real, c.imag  # (2.0, 3.0)\nTrue + True     # 2  — bool is an int subclass\n```\n\nWhy it matters: mixing types **promotes** to the wider one (`int + float -> float`),\nand knowing the three types explains conversion and precision behavior.\n",{"id":5024,"difficulty":63,"q":5025,"a":5026},"division-floor-modulo","How do `\u002F`, `\u002F\u002F`, and `%` behave, especially with negatives?","`\u002F` is **true division** and always returns a `float`. `\u002F\u002F` is **floor division**\n— it rounds **toward negative infinity**, not toward zero. `%` is the matching\nmodulo, and in Python its **result takes the sign of the divisor**.\n\n```python\n7 \u002F 2       # 3.5    — always float\n7 \u002F\u002F 2      # 3\n-7 \u002F\u002F 2     # -4     — floors toward -infinity, not -3\n-7 % 2      # 1      — sign follows the divisor (2)\n7 % -2      # -1     — sign follows the divisor (-2)\n```\n\nThe identity always holds: `(a \u002F\u002F b) * b + (a % b) == a`. Rule of thumb: Python's\nfloor\u002Fmodulo differ from C\u002FJava for negatives — expect non-negative `%` when the\ndivisor is positive.\n",{"id":5028,"difficulty":71,"q":5029,"a":5030},"int-arbitrary-precision","Why don't Python integers overflow?","Python `int` has **arbitrary precision** — it grows to hold any value, limited only\nby available memory. There is no fixed 32\u002F64-bit width, so computations never\nsilently wrap around like in C or Java.\n\n```python\n2 ** 100        # 1267650600228229401496703205376\nx = 10 ** 1000  # a 1001-digit integer — no overflow\nimport sys\nsys.maxsize     # largest \"native\" int, but ints can exceed it freely\n```\n\nWhy it matters: you can compute huge factorials or cryptographic numbers directly,\nbut very large ints cost more memory and arithmetic gets slower. Rule of thumb:\ninteger overflow is simply not a concern in Python.\n",{"id":5032,"difficulty":63,"q":5033,"a":5034},"float-precision-decimal","Why is 0.1 + 0.2 not exactly 0.3?","Floats are stored in **binary (IEEE 754)**, and values like 0.1 and 0.2 have no\nexact binary representation — so tiny rounding errors accumulate. This is inherent\nto binary floating point, not a Python bug.\n\n```python\n0.1 + 0.2            # 0.30000000000000004\n0.1 + 0.2 == 0.3     # False\nround(0.1 + 0.2, 2)  # 0.3   — round for display\nimport math\nmath.isclose(0.1 + 0.2, 0.3)   # True — tolerant comparison\n\nfrom decimal import Decimal\nDecimal(\"0.1\") + Decimal(\"0.2\")   # Decimal('0.3')  — exact\n```\n\nRule of thumb: never compare floats with `==`; use `math.isclose` or round, and\nreach for **`Decimal`** when you need exact decimal arithmetic (e.g. money).\n",{"id":5036,"difficulty":63,"q":5037,"a":5038},"bitwise-operators","What are Python's bitwise operators?","Bitwise operators work on the binary representation of integers: **`&`** (and),\n**`|`** (or), **`^`** (xor), **`~`** (not\u002Finvert), **`\u003C\u003C`** (left shift), and\n**`>>`** (right shift). Shifting left by `n` multiplies by `2**n`.\n\n```python\n5 & 3    # 1   (0b101 & 0b011)\n5 | 3    # 7   (0b111)\n5 ^ 3    # 6   (0b110)\n~5       # -6  (~x == -(x+1))\n1 \u003C\u003C 4   # 16  (1 * 2**4)\n20 >> 2  # 5   (20 \u002F\u002F 4)\n```\n\nWhy it matters: bitwise ops power flags\u002Fbitmasks, fast power-of-two math, and\nlow-level protocols. Rule of thumb: `~x` equals `-(x + 1)` because of two's\ncomplement.\n",{"id":5040,"difficulty":71,"q":5041,"a":5042},"divmod-and-power","What do `divmod` and `**` do?","**`divmod(a, b)`** returns the quotient and remainder as a single tuple\n`(a \u002F\u002F b, a % b)` in one call. **`**`** is exponentiation; with a third argument,\nthe built-in `pow(base, exp, mod)` does efficient modular exponentiation.\n\n```python\ndivmod(17, 5)     # (3, 2)  — quotient and remainder together\n2 ** 10           # 1024\npow(2, 10)        # 1024  — same as **\npow(2, 10, 1000)  # 24    — (2**10) % 1000, computed efficiently\n```\n\nRule of thumb: use `divmod` when you need both results (e.g. converting seconds to\nminutes\u002Fseconds), and `pow(a, b, m)` for modular math instead of `(a ** b) % m`.\n",{"description":61},"Python interview questions on int\u002Ffloat\u002Fcomplex, floor division and modulo with negatives, arbitrary precision, float precision, bitwise operators, and divmod.","python\u002Ffundamentals\u002Fnumbers-operators","Numbers & Operators","y_gRkCXYAeOaIuz3yr39UOW1-0X0sEQJiimG2onF8sA",{"id":5049,"title":5050,"body":5051,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5055,"navigation":66,"order":22,"path":5056,"questions":5057,"related":207,"seo":5077,"seoDescription":5078,"stem":5079,"subtopic":5080,"topic":667,"topicSlug":668,"updated":214,"__hash__":5081},"qa\u002Fpython\u002Ffundamentals\u002Fscope-legb.md","Scope Legb",{"type":58,"value":5052,"toc":5053},[],{"title":61,"searchDepth":22,"depth":22,"links":5054},[],{},"\u002Fpython\u002Ffundamentals\u002Fscope-legb",[5058,5062,5066,5070,5073],{"id":5059,"difficulty":63,"q":5060,"a":5061},"legb-rule","What is the LEGB rule?","**LEGB** describes the order Python searches for a name: **Local** (inside the\ncurrent function), **Enclosing** (any outer functions), **Global** (the module's\ntop level), then **Built-in** (names like `len`, `print`). The first match wins,\nand the search stops there.\n\n```python\nx = \"global\"\ndef outer():\n    x = \"enclosing\"\n    def inner():\n        x = \"local\"\n        print(x)     # \"local\"  — Local found first\n    inner()\nouter()\n```\n\nWhy it matters: nearly every \"why is this variable that value?\" question reduces\nto walking **L -> E -> G -> B** until a name is found.\n",{"id":5063,"difficulty":63,"q":5064,"a":5065},"global-vs-nonlocal","What is the difference between `global` and `nonlocal`?","Both let you **rebind** a name from an outer scope instead of creating a new local.\n`global` targets the **module-level** name; `nonlocal` targets the **nearest\nenclosing function** scope (and that name must already exist there).\n\n```python\ncount = 0\ndef inc():\n    global count\n    count += 1        # rebinds module-level count\n\ndef outer():\n    x = 1\n    def inner():\n        nonlocal x\n        x = 2          # rebinds outer's x, not a new local\n    inner()\n    return x           # 2\n```\n\nRule of thumb: you only need these keywords to **reassign** an outer name — you can\nalways *mutate* an outer mutable object (e.g. `list.append`) without them.\n",{"id":5067,"difficulty":84,"q":5068,"a":5069},"unbound-local-error","Why does assigning to a name make it local and cause UnboundLocalError?","Python decides a name's scope **at compile time** by scanning the whole function\nbody. If a name is **assigned anywhere** in a function, it is treated as **local\nfor the entire function** — even on lines before the assignment. Reading it before\nit's bound raises **UnboundLocalError**.\n\n```python\nx = 10\ndef f():\n    print(x)      # UnboundLocalError: x is local because of the line below\n    x = 20        # this assignment makes x local everywhere in f\n```\n\nThe fix is to declare `global x` (or `nonlocal x`) if you meant the outer name, or\nsimply read a different name. Rule of thumb: **an assignment anywhere makes the\nname local everywhere** in that function.\n",{"id":5071,"difficulty":84,"q":4783,"a":5072},"late-binding-closures","Closures capture **variables, not values** — this is **late binding**. The inner\nfunction looks up the loop variable **when it is called**, by which time the loop\nhas finished and the variable holds its final value.\n\n```python\nfuncs = [lambda: i for i in range(3)]\n[f() for f in funcs]      # [2, 2, 2]  — all see the final i\n\n# Fix: bind the current value via a default argument\nfuncs = [lambda i=i: i for i in range(3)]\n[f() for f in funcs]      # [0, 1, 2]\n```\n\nThe default-argument trick captures `i`'s value at definition time. Rule of thumb:\nif loop-created closures behave strangely, you're hitting late binding — bind the\nvalue explicitly.\n",{"id":5074,"difficulty":63,"q":5075,"a":5076},"module-vs-function-shadowing","How does name shadowing work between module and function scope?","A local name **shadows** (hides) an outer name of the same identity for the\nduration of the scope. Assigning to it inside a function creates a separate local\nthat leaves the **module-level** name untouched.\n\n```python\nvalue = \"module\"\ndef f():\n    value = \"function\"   # new local — shadows the global\n    print(value)         # \"function\"\nf()\nprint(value)             # \"module\"  — unchanged\n\nlist = [1, 2]            # shadows the built-in list() in this scope!\n```\n\nWatch out for shadowing **built-ins** (`list`, `id`, `sum`, `type`) — it silently\nbreaks later calls. Rule of thumb: keep names distinct from outer scopes and\nbuilt-ins to avoid surprising lookups.\n",{"description":61},"Python interview questions on the LEGB scope rule, global vs nonlocal, UnboundLocalError, late binding in loop closures, and name shadowing.","python\u002Ffundamentals\u002Fscope-legb","Variables, Scope & the LEGB Rule","Dpt_Q0OFjMvd7AoVKH6T5OWFzpQa5ln0EU8zsuvK55I",{"id":5083,"title":5084,"body":5085,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5089,"navigation":66,"order":40,"path":5090,"questions":5091,"related":207,"seo":5116,"seoDescription":5117,"stem":5118,"subtopic":5119,"topic":667,"topicSlug":668,"updated":214,"__hash__":5120},"qa\u002Fpython\u002Ffundamentals\u002Fstrings-formatting.md","Strings Formatting",{"type":58,"value":5086,"toc":5087},[],{"title":61,"searchDepth":22,"depth":22,"links":5088},[],{},"\u002Fpython\u002Ffundamentals\u002Fstrings-formatting",[5092,5096,5100,5104,5108,5112],{"id":5093,"difficulty":63,"q":5094,"a":5095},"fstring-vs-format-vs-percent","What is the difference between f-strings, .format(), and % formatting?","All three interpolate values into strings. **`%`** is the oldest C-style syntax.\n**`str.format()`** uses `{}` placeholders and is more flexible. **f-strings**\n(Python 3.6+) embed expressions **inline** and are the fastest and most readable.\n\n```python\nname, n = \"Ada\", 3\n\"Hi %s, %d items\" % (name, n)        # old % style\n\"Hi {}, {} items\".format(name, n)    # str.format\nf\"Hi {name}, {n} items\"              # f-string — preferred\nf\"{n * 2 = }\"                        # \"n * 2 = 6\"  — self-documenting\n```\n\nRule of thumb: prefer **f-strings** for new code — they evaluate expressions\ndirectly and avoid the argument-ordering errors of `%` and `.format()`.\n",{"id":5097,"difficulty":63,"q":5098,"a":5099},"str-vs-bytes","What is the difference between str and bytes?","A **`str`** is a sequence of **Unicode code points** (text); **`bytes`** is a\nsequence of **raw bytes** (0-255). You convert between them with **`encode`**\n(str -> bytes) and **`decode`** (bytes -> str), specifying an encoding like UTF-8.\n\n```python\ns = \"café\"\nb = s.encode(\"utf-8\")    # b'caf\\xc3\\xa9'  — 5 bytes (é is 2)\nb.decode(\"utf-8\")        # \"café\"  — back to text\nlen(s), len(b)           # (4, 5)\ns + b                    # TypeError — can't mix str and bytes\n```\n\nWhy it matters: files and network sockets deal in **bytes**, your program logic in\n**str**. Rule of thumb: decode bytes to str as early as possible and encode back to\nbytes only at the I\u002FO boundary.\n",{"id":5101,"difficulty":71,"q":5102,"a":5103},"common-string-methods","What are the common string methods like split, strip, and join?","**`split`** breaks a string into a list on a separator; **`strip`** removes\nleading\u002Ftrailing whitespace (or given characters); **`join`** glues an iterable of\nstrings together with a separator. All return **new** strings since `str` is\nimmutable.\n\n```python\n\"  a,b,c  \".strip()            # \"a,b,c\"\n\"a,b,c\".split(\",\")            # [\"a\", \"b\", \"c\"]\n\",\".join([\"a\", \"b\", \"c\"])     # \"a,b,c\"\n\"Hello\".lower(), \"Hi\".upper() # (\"hello\", \"HI\")\n\"hello\".replace(\"l\", \"L\")     # \"heLLo\"\n```\n\nRule of thumb: `sep.join(list)` is the inverse of `text.split(sep)`, and chaining\nthese covers most everyday text wrangling.\n",{"id":5105,"difficulty":63,"q":5106,"a":5107},"join-vs-concat-loop","Why use join instead of += to build a string in a loop?","Strings are **immutable**, so each `+=` creates a **brand-new string** and copies\neverything so far — turning a loop into O(n^2) work and lots of garbage. **`join`**\nallocates the result **once**, making it O(n).\n\n```python\n# Slow — new string every iteration\nresult = \"\"\nfor word in words:\n    result += word\n\n# Fast — single allocation\nresult = \"\".join(words)\n```\n\nRule of thumb: collect pieces in a list (or generator) and call `\"\".join(...)` —\nit's the Python equivalent of a `StringBuilder`.\n",{"id":5109,"difficulty":71,"q":5110,"a":5111},"raw-strings","What is a raw string and when do you use it?","A **raw string** (`r\"...\"`) tells Python **not to process backslash escapes**, so\n`\\n`, `\\t`, etc. stay as literal backslash-plus-character. They're ideal for\n**regular expressions** and **Windows file paths**.\n\n```python\nprint(\"a\\tb\")    # a    b   — \\t is a tab\nprint(r\"a\\tb\")   # a\\tb     — backslash kept literally\n\nimport re\nre.findall(r\"\\d+\", \"x12y3\")   # ['12', '3']  — no double-backslashing\npath = r\"C:\\Users\\name\"       # backslashes stay intact\n```\n\nRule of thumb: reach for `r\"...\"` whenever your string is full of backslashes —\nit avoids the noise and bugs of escaping every one.\n",{"id":5113,"difficulty":63,"q":5114,"a":5115},"format-spec-mini-language","How does the format spec mini-language work (padding, :.2f)?","Inside `{}` (or after `:` in `format`), a **format spec** controls alignment,\nwidth, and precision: `{value:[fill][align][width][,][.precision][type]}`. It\nworks in f-strings and `str.format` alike.\n\n```python\nf\"{42:5}\"        # \"   42\"    — width 5, right-aligned (default for numbers)\nf\"{'hi':\u003C5}|\"    # \"hi   |\"   — left-align in width 5\nf\"{'hi':^5}|\"    # \" hi  |\"   — center\nf\"{42:05}\"       # \"00042\"    — zero-padded\nf\"{3.14159:.2f}\" # \"3.14\"     — 2 decimal places\nf\"{1234567:,}\"   # \"1,234,567\"  — thousands separator\nf\"{0.25:.1%}\"    # \"25.0%\"    — percentage\n```\n\nRule of thumb: `.2f` controls decimals, a number sets width, and `\u003C`\u002F`>`\u002F`^` set\nalignment — combine them for clean tabular output.\n",{"description":61},"Python interview questions on f-strings vs .format vs %, str vs bytes, common string methods, join vs +=, raw strings, and the format spec mini-language.","python\u002Ffundamentals\u002Fstrings-formatting","Strings & String Formatting","Fly7brM0I0JbkO0F5-ZVq4BC9z9GcKpnaukrHV5K3lA",{"id":5122,"title":5123,"body":5124,"description":61,"difficulty":71,"extension":64,"framework":30,"frameworkSlug":28,"meta":5128,"navigation":66,"order":50,"path":5129,"questions":5130,"related":207,"seo":5155,"seoDescription":5156,"stem":5157,"subtopic":5158,"topic":667,"topicSlug":668,"updated":214,"__hash__":5159},"qa\u002Fpython\u002Ffundamentals\u002Ftruthiness-conversion.md","Truthiness Conversion",{"type":58,"value":5125,"toc":5126},[],{"title":61,"searchDepth":22,"depth":22,"links":5127},[],{},"\u002Fpython\u002Ffundamentals\u002Ftruthiness-conversion",[5131,5135,5139,5143,5147,5151],{"id":5132,"difficulty":71,"q":5133,"a":5134},"falsy-values","Which values are falsy in Python?","A handful of values are **falsy** (treated as `False` in a boolean context):\n**`None`**, **`False`**, **zero** of any numeric type (`0`, `0.0`, `0j`), and\n**empty containers\u002Fsequences** (`\"\"`, `[]`, `{}`, `()`, `set()`, `range(0)`).\nAlmost everything else is **truthy**.\n\n```python\nbool(0), bool(\"\"), bool([]), bool(None)   # all False\nbool(1), bool(\"x\"), bool([0]), bool(\" \")  # all True\nif not items:        # idiomatic empty check\n    print(\"empty\")\n```\n\nWhy it matters: idiomatic Python uses `if items:` rather than `if len(items) > 0:`.\nRule of thumb: \"empty or zero or None\" is falsy; everything else is truthy.\n",{"id":5136,"difficulty":63,"q":5137,"a":5138},"bool-len-protocol","How does Python decide whether a custom object is truthy?","Python calls **`__bool__`** first; if it's not defined, it falls back to\n**`__len__`** (zero length is falsy). If neither exists, the object is **always\ntruthy** — the default for plain instances.\n\n```python\nclass Box:\n    def __init__(self, items): self.items = items\n    def __len__(self): return len(self.items)   # used for truthiness\n\nbool(Box([]))     # False — __len__ is 0\nbool(Box([1]))    # True\n\nclass Always:\n    def __bool__(self): return False   # __bool__ wins over __len__\nbool(Always())    # False\n```\n\nRule of thumb: define `__bool__` (or `__len__`) so `if obj:` makes sense for your\ntype; otherwise every instance is truthy.\n",{"id":5140,"difficulty":71,"q":5141,"a":5142},"explicit-conversion","How do explicit type conversions like int(), str(), and list() work?","Python provides **constructor functions** that convert between types: `int()`,\n`float()`, `str()`, `bool()`, `list()`, `tuple()`, `set()`, `dict()`. They build a\n**new** object and raise `ValueError` if the input can't be converted.\n\n```python\nint(\"42\")        # 42\nint(\"3.9\")       # ValueError — not a valid int literal\nint(3.9)         # 3   — truncates toward zero\nfloat(\"3.14\")    # 3.14\nstr(255)         # \"255\"\nlist(\"abc\")      # ['a', 'b', 'c']\nlist({1: \"a\"})   # [1]  — iterates keys\n```\n\nRule of thumb: these are **explicit** conversions you call yourself — Python rarely\nconverts types implicitly, so reach for the constructor you need.\n",{"id":5144,"difficulty":71,"q":5145,"a":5146},"empty-container-truthiness","Are empty containers and None falsy?","Yes. Every **empty** built-in container is falsy — `[]`, `{}`, `()`, `set()`,\n`\"\"` — and so is **`None`**. A non-empty container is truthy regardless of what it\ncontains, even `[0]` or `[False]`.\n\n```python\nbool([]), bool({}), bool(set()), bool(\"\")   # all False\nbool([0]), bool([False]), bool({None})       # all True — non-empty!\nbool(None)                                   # False\n```\n\nWatch the trap: `[0]` is **truthy** because it has one element, even though that\nelement is falsy. Rule of thumb: container truthiness depends on **length**, not on\nthe elements' values.\n",{"id":5148,"difficulty":63,"q":5149,"a":5150},"and-or-short-circuit","What do `and` and `or` actually return?","`and`\u002F`or` **short-circuit** and return one of their **operands**, not a strict\n`True`\u002F`False`. `and` returns the **first falsy** operand (or the last if all are\ntruthy); `or` returns the **first truthy** operand (or the last if all are falsy).\n\n```python\n0 and 5         # 0   — first falsy, second never evaluated\n2 and 5         # 5   — both truthy, returns last\n0 or \"default\"  # \"default\"  — first truthy\nNone or 0 or [] # []  — all falsy, returns the last\nname = user_input or \"guest\"   # common default idiom\n```\n\nRule of thumb: `x or default` supplies a fallback, and short-circuiting means the\nright side is skipped when the result is already decided.\n",{"id":5152,"difficulty":71,"q":5153,"a":5154},"is-none-vs-eq-none","Why use `is None` instead of `== None`?","`None` is a **singleton** — there is exactly one `None` object — so `is None`\nchecks **identity**, which is fast and can't be fooled. `== None` calls `__eq__`,\nwhich a class can **override** to return a misleading result.\n\n```python\nif x is None:        # idiomatic, reliable\n    ...\n\nclass Weird:\n    def __eq__(self, other): return True\nWeird() == None      # True   — misleading!\nWeird() is None      # False  — correct\n```\n\nRule of thumb: always compare against `None`, `True`, and `False` with **`is`\u002F\n`is not`** — PEP 8 explicitly recommends it.\n",{"description":61},"Python interview questions on falsy values, __bool__\u002F__len__, explicit type conversion, truthiness of empty containers, short-circuiting and\u002For, and is None vs == None.","python\u002Ffundamentals\u002Ftruthiness-conversion","Truthiness & Type Conversion","H0Pq-9nSUmc-J53irQW_l_BUHoaEHBvAnRvB87cpL4I",{"id":5161,"title":5162,"body":5163,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5167,"navigation":66,"order":12,"path":5168,"questions":5169,"related":207,"seo":5190,"seoDescription":5191,"stem":5192,"subtopic":5193,"topic":5194,"topicSlug":5195,"updated":214,"__hash__":5196},"qa\u002Fpython\u002Fidioms\u002Feafp-lbyl.md","Eafp Lbyl",{"type":58,"value":5164,"toc":5165},[],{"title":61,"searchDepth":22,"depth":22,"links":5166},[],{},"\u002Fpython\u002Fidioms\u002Feafp-lbyl",[5170,5174,5178,5182,5186],{"id":5171,"difficulty":71,"q":5172,"a":5173},"eafp-lbyl-meaning","What do EAFP and LBYL mean?","**EAFP** = \"**Easier to Ask Forgiveness than Permission**\": just **attempt**\nthe operation and handle the exception if it fails. **LBYL** = \"**Look Before\nYou Leap**\": **check** the preconditions first, then act only if the checks\npass. They are two styles for handling things that *might* go wrong.\n\n```python\n# LBYL — check first\nif \"key\" in config:\n    value = config[\"key\"]\n\n# EAFP — try and handle failure\ntry:\n    value = config[\"key\"]\nexcept KeyError:\n    value = default\n```\n\nEAFP is the **Pythonic** default — it reads naturally and avoids redundant\nchecks. Rule of thumb: in Python, **try the operation and catch the specific\nexception** rather than pre-validating every condition.\n",{"id":5175,"difficulty":63,"q":5176,"a":5177},"why-eafp-preferred","Why is EAFP preferred in Python?","EAFP fits Python's design: exceptions are **cheap** and **idiomatic**, and the\nstyle avoids **duplicating logic**. With LBYL you often check a condition and\nthen perform the same lookup\u002Foperation again, doing the work twice. EAFP also\nstays correct when an object merely **behaves like** the expected type\n(duck typing) rather than passing an explicit type check.\n\n```python\n# LBYL duplicates the access and breaks on duck-typed objects\nif hasattr(obj, \"read\") and callable(obj.read):\n    data = obj.read()\n\n# EAFP — just use it; let the exception surface real problems\ntry:\n    data = obj.read()\nexcept AttributeError:\n    data = None\n```\n\nThe happy path stays uncluttered and the error handling is explicit. Rule of\nthumb: write the **common case** as straight-line code and catch the\n**specific** exception for the rare failure.\n",{"id":5179,"difficulty":84,"q":5180,"a":5181},"lbyl-race-condition","What race condition does LBYL invite?","LBYL introduces a **TOCTOU** bug — \"**Time Of Check to Time Of Use**\". Between\nthe moment you **check** a condition and the moment you **act** on it, another\nthread or process can change the state, so the check is **stale** and the\naction fails or corrupts data. EAFP avoids the gap by acting atomically and\nhandling failure.\n\n```python\nimport os\n# LBYL — file can be deleted between the check and the open (race!)\nif os.path.exists(path):\n    with open(path) as f:    # may still raise FileNotFoundError\n        data = f.read()\n\n# EAFP — no window; the open either works or raises\ntry:\n    with open(path) as f:\n        data = f.read()\nexcept FileNotFoundError:\n    data = None\n```\n\nThe check-then-act pattern is unsafe in concurrent or filesystem contexts.\nRule of thumb: for files, sockets, and shared state, **attempt the operation**\nand handle the exception rather than checking first.\n",{"id":5183,"difficulty":63,"q":5184,"a":5185},"dict-get-vs-check","When should you use dict.get versus checking for a key?","`dict.get(key, default)` returns the value if present and the **default**\n(`None` if unspecified) otherwise — a clean one-liner that avoids both the\n`if key in d` check **and** a `try\u002Fexcept KeyError`. Use a membership check or\n`try\u002Fexcept` only when you must **distinguish a missing key from a stored\n`None`**, or run different logic in each branch.\n\n```python\ncounts = {\"a\": 1}\ncounts.get(\"b\")          # None — no KeyError\ncounts.get(\"b\", 0)       # 0    — supply a default\n\n# need to tell \"missing\" from \"stored None\"? then check explicitly\nif \"b\" in counts:\n    ...\n# or accumulate with setdefault \u002F defaultdict\ncounts.setdefault(\"c\", 0)\n```\n\nFor counting\u002Fgrouping, `collections.defaultdict` or `Counter` is even cleaner.\nRule of thumb: reach for `.get()` with a default for \"value or fallback\", and\nonly branch explicitly when missing-ness itself is meaningful.\n",{"id":5187,"difficulty":84,"q":5188,"a":5189},"eafp-pitfalls","What are the pitfalls of EAFP, and how do you avoid them?","EAFP done carelessly causes two problems. First, a **too-broad `except`**\n(bare `except:` or `except Exception`) can **swallow unrelated bugs** —\ncatching a `KeyError` you didn't intend, or hiding a `NameError`. Second, the\n`try` block should wrap **only** the line that can fail, so you don't\naccidentally catch exceptions from surrounding code.\n\n```python\n# Bad — hides real errors and over-wide try block\ntry:\n    value = config[\"key\"]\n    result = expensive_call(value)   # its errors get caught too!\nexcept Exception:\n    value = default\n\n# Good — narrow exception, minimal try body\ntry:\n    value = config[\"key\"]\nexcept KeyError:\n    value = default\nresult = expensive_call(value)       # outside the try\n```\n\nAlways catch the **most specific** exception and keep the `try` body small.\nRule of thumb: EAFP means \"catch the *one* expected failure\", never \"catch\neverything and hope\".\n",{"description":61},"Python interview questions on EAFP vs LBYL, why try\u002Fexcept is preferred, the race conditions LBYL invites, and dict.get versus checking for a key.","python\u002Fidioms\u002Feafp-lbyl","EAFP vs LBYL","Pythonic Idioms","idioms","bCZ-XKDsdon8EdwPgbyY1qZW_3AfSyoMZOhOsdPFSIw",{"id":5198,"title":5199,"body":5200,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5204,"navigation":66,"order":31,"path":5205,"questions":5206,"related":207,"seo":5233,"seoDescription":5234,"stem":5235,"subtopic":5236,"topic":5194,"topicSlug":5195,"updated":214,"__hash__":5237},"qa\u002Fpython\u002Fidioms\u002Fgotchas.md","Gotchas",{"type":58,"value":5201,"toc":5202},[],{"title":61,"searchDepth":22,"depth":22,"links":5203},[],{},"\u002Fpython\u002Fidioms\u002Fgotchas",[5207,5211,5214,5218,5222,5225,5229],{"id":5208,"difficulty":84,"q":5209,"a":5210},"mutable-default-arg","Why is a mutable default argument a gotcha?","A default argument is **evaluated once when the function is defined**, not on each\ncall. So a mutable default like `[]` or `{}` is **created a single time and shared**\nacross every call that doesn't override it — state leaks between calls.\n\n```python\ndef append_to(item, target=[]):   # the SAME list every call\n    target.append(item)\n    return target\n\nappend_to(1)   # [1]\nappend_to(2)   # [1, 2]  \u003C- surprise!\n\ndef append_to(item, target=None): # the fix: None sentinel\n    if target is None:\n        target = []               # fresh list per call\n    target.append(item)\n    return target\n```\n\nUse **`None` as the default** and create the real object inside the body. This is the\nsingle most famous Python footgun.\n",{"id":5071,"difficulty":84,"q":5212,"a":5213},"What is the late-binding closure gotcha in loops?","Closures in Python capture **variables by reference, not by value**. When you create\nfunctions in a loop, they all close over the **same** loop variable, which holds its\n**final value** by the time they're called.\n\n```python\nfuncs = [lambda: i for i in range(3)]\n[f() for f in funcs]          # [2, 2, 2]  — not [0, 1, 2]!\n\n# fix: bind the current value via a default argument\nfuncs = [lambda i=i: i for i in range(3)]\n[f() for f in funcs]          # [0, 1, 2]\n```\n\nThe default-argument trick captures `i`'s value **at definition time**. (`functools.\npartial` works too.) Remember: closures see the variable's *latest* value, not a\nsnapshot.\n",{"id":5215,"difficulty":63,"q":5216,"a":5217},"modify-while-iterating","What goes wrong when you modify a list while iterating it?","Changing a list's **size during iteration** shifts the internal index, causing\nelements to be **skipped or repeated**. With dicts and sets it's worse — Python\nraises `RuntimeError: dictionary changed size during iteration`.\n\n```python\nnums = [1, 2, 3, 4]\nfor n in nums:\n    if n % 2 == 0:\n        nums.remove(n)        # skips elements — buggy\nprint(nums)                   # [1, 3] for some inputs, wrong for others\n\nnums = [n for n in nums if n % 2]   # build a new list instead\n```\n\nFix it by iterating over a **copy** (`for n in nums[:]`) or, better, building a new\ncollection with a comprehension or `filter`. Never mutate a container's size while\nlooping over it.\n",{"id":5219,"difficulty":63,"q":5220,"a":5221},"is-vs-eq-cached","Why does `is` give surprising results on numbers and strings?","`is` tests **identity** (same object), while `==` tests **value**. CPython **caches**\nsmall integers (−5 to 256) and **interns** some strings, so `is` *coincidentally*\nreturns `True` for those — but fails for values outside the cache, making it look\nunreliable.\n\n```python\na = 256; b = 256\na is b          # True  — cached\n\nc = 1000; d = 1000\nc is d          # often False — not cached\nc == d          # True   — always correct\n\nx = \"hi\"; y = \"hi\"\nx is y          # True (interned) — don't rely on it\n```\n\nCaching is an **implementation detail**, not a guarantee. Rule: use `==` for value\ncomparison; reserve `is` for singletons (`None`, `True`, `False`).\n",{"id":4592,"difficulty":63,"q":5223,"a":5224},"Why is a bare except an anti-pattern?","A bare **`except:`** (or `except Exception:` used carelessly) catches **everything** —\nincluding `KeyboardInterrupt` and `SystemExit` — and **swallows the error silently**,\nhiding bugs and making programs impossible to interrupt or debug.\n\n```python\ntry:\n    risky()\nexcept:                  # catches EVERYTHING, even Ctrl-C\n    pass                 # error vanishes — undebuggable\n\ntry:\n    risky()\nexcept ValueError as e:  # catch only what you expect\n    log.error(\"bad value: %s\", e)\n    raise                # or handle it deliberately\n```\n\nCatch the **specific exceptions** you can actually handle, and avoid `pass` in an\n`except` (at minimum log it). If you must catch broadly, use `except Exception` (not\nbare) so system-exiting signals still propagate.\n",{"id":5226,"difficulty":84,"q":5227,"a":5228},"mutable-class-attr","Why is a mutable class attribute a common bug?","A mutable value assigned **at class level** (outside `__init__`) is **one object\nshared by every instance**. Mutating it through any instance affects **all** of them\n— usually not what you intend.\n\n```python\nclass Cart:\n    items = []                  # SHARED across all instances\n    def add(self, x):\n        self.items.append(x)\n\na, b = Cart(), Cart()\na.add(\"apple\")\nb.items                         # ['apple'] — leaked into b!\n\nclass Cart:\n    def __init__(self):\n        self.items = []         # per-instance — correct\n```\n\nInitialize mutable attributes **inside `__init__`** so each instance gets its own.\nClass-level attributes are fine for **immutable** constants\u002Fdefaults, but never for\nmutable per-instance state.\n",{"id":5230,"difficulty":71,"q":5231,"a":5232},"shadowing-builtins","What is the problem with shadowing builtins?","Naming a variable after a builtin — `list`, `dict`, `id`, `str`, `type`, `sum` —\n**shadows** it in that scope, so the original becomes unusable and you get confusing\nerrors later when you try to call it.\n\n```python\nlist = [1, 2, 3]          # shadows the built-in list type\nother = list((4, 5))      # TypeError: 'list' object is not callable\n\nid = 42                   # now id() is gone\nid(other)                 # TypeError: 'int' object is not callable\n```\n\nPick non-conflicting names: `items`\u002F`values` instead of `list`, `mapping` instead of\n`dict`, `user_id` instead of `id`. Linters flag builtin shadowing — heed the warning\nto avoid these baffling bugs.\n",{"description":61},"Python interview questions on common gotchas: mutable default arguments, late-binding closures, modifying a list while iterating, is vs ==, bare except, mutable class attributes, and shadowing builtins.","python\u002Fidioms\u002Fgotchas","Common Gotchas & Anti-patterns","dQ6TWsvM0wnn7CS37n3Xav6bFViKq0g1Er9l_hofq4c",{"id":5239,"title":5240,"body":5241,"description":61,"difficulty":71,"extension":64,"framework":30,"frameworkSlug":28,"meta":5245,"navigation":66,"order":22,"path":5246,"questions":5247,"related":207,"seo":5272,"seoDescription":5273,"stem":5274,"subtopic":5275,"topic":5194,"topicSlug":5195,"updated":214,"__hash__":5276},"qa\u002Fpython\u002Fidioms\u002Fpep8-style.md","Pep8 Style",{"type":58,"value":5242,"toc":5243},[],{"title":61,"searchDepth":22,"depth":22,"links":5244},[],{},"\u002Fpython\u002Fidioms\u002Fpep8-style",[5248,5252,5256,5260,5264,5268],{"id":5249,"difficulty":71,"q":5250,"a":5251},"what-is-pep8","What is PEP 8?","**PEP 8** is the official **style guide for Python code** — a set of conventions for\nformatting and naming that make code **consistent and readable** across the\ncommunity. It's a *recommendation*, not a language rule: code that violates PEP 8\nstill runs fine, but consistency aids collaboration.\n\n```python\n# PEP 8 style\ndef calculate_total(items, tax_rate=0.0):\n    subtotal = sum(items)\n    return subtotal * (1 + tax_rate)\n\n# not PEP 8 — cramped, inconsistent spacing\u002Fnaming\ndef calcTotal(items,taxRate=0.0):\n    subTotal=sum(items);return subTotal*(1+taxRate)\n```\n\nPEP 8 covers indentation (4 spaces), naming, whitespace, imports, and line length.\nIts guiding principle: **readability counts**, since code is read far more often than\nit's written.\n",{"id":5253,"difficulty":71,"q":5254,"a":5255},"naming-conventions","What are PEP 8's naming conventions?","PEP 8 assigns a distinct case to each kind of name so readers can tell them apart at\na glance. **`snake_case`** for functions, variables, and modules;\n**`PascalCase`** (CapWords) for classes; **`UPPER_SNAKE_CASE`** for constants. A\nsingle leading underscore signals \"internal\".\n\n```python\nMAX_RETRIES = 3                  # constant — UPPER_SNAKE_CASE\n\nclass HttpClient:                # class — PascalCase\n    def send_request(self):      # method — snake_case\n        retry_count = 0          # variable — snake_case\n        self._session = None     # _leading underscore = \"internal\"\n```\n\nAvoid single-character names like `l`, `O`, `I` (they look like digits). Method\u002F\nfunction names use the same `snake_case` as variables; only classes and exceptions\nuse `PascalCase`.\n",{"id":5257,"difficulty":71,"q":5258,"a":5259},"imports-line-length","What does PEP 8 say about imports and line length?","**Imports** go at the **top** of the file, **one per line**, grouped in order:\nstandard library, third-party, then local — separated by blank lines. For **line\nlength**, PEP 8 recommends a maximum of **79 characters** (72 for docstrings\u002F\ncomments), though many modern teams relax this to 88 or 100.\n\n```python\n# standard library\nimport os\nimport sys\n\n# third-party\nimport requests\n\n# local\nfrom myapp.utils import helper\n\n# avoid: import os, sys   (multiple on one line)\n```\n\nKeeping imports sorted and grouped makes dependencies obvious. The line-length cap\nkeeps code readable in side-by-side diffs and narrow editors; tools like `isort`\nautomate import ordering.\n",{"id":5261,"difficulty":71,"q":5262,"a":5263},"zen-of-python","What is the Zen of Python?","The **Zen of Python** (PEP 20) is a collection of **19 guiding aphorisms** that\ncapture Python's design philosophy. You can read it any time by running\n**`import this`**. It informs *why* the language and its idioms look the way they do.\n\n```python\nimport this\n# Beautiful is better than ugly.\n# Explicit is better than implicit.\n# Simple is better than complex.\n# Readability counts.\n# There should be one-- and preferably only one --obvious way to do it.\n# ...and 14 more\n```\n\nThe aphorisms favor **clarity, simplicity, and explicitness** over cleverness. They\naren't enforced rules but a cultural compass — when two approaches compete, the Zen\nusually points to the more Pythonic one.\n",{"id":5265,"difficulty":71,"q":5266,"a":5267},"formatters-linters","What are black and ruff, and how do formatters differ from linters?","A **formatter** automatically **rewrites** your code into a consistent layout; a\n**linter** **analyzes** code and **reports** style violations and likely bugs without\n(usually) changing it. **black** is the dominant formatter (opinionated,\nnear-zero-config); **ruff** is an extremely fast linter (and formatter) that\nconsolidates many older tools.\n\n```python\n# before black\nx = {'a':1,'b':2}\n# after black\nx = {\"a\": 1, \"b\": 2}\n\n# command line\n# black .          -> reformats files in place\n# ruff check .     -> reports lint issues\n# ruff check --fix -> auto-fixes what it can\n```\n\nRunning a formatter ends style arguments in code review (the tool decides), while a\nlinter catches unused imports, undefined names, and anti-patterns. Most teams run\nboth, often automatically via pre-commit hooks or CI.\n",{"id":5269,"difficulty":63,"q":5270,"a":5271},"when-break-pep8","When is it acceptable to break PEP 8?","PEP 8 itself says **\"A Foolish Consistency is the Hobgoblin of Little Minds\"** —\nstyle serves readability, so break the rules when following them would make code\n**less readable** or when you must stay consistent with **surrounding code** or an\nexisting API.\n\n```python\n# matching an external library's camelCase API\ndef setUp(self):           # unittest requires this exact name\n    ...\n\n# aligning related assignments can aid readability in some cases\nx      = 1\nlonger = 2\n```\n\nLegitimate reasons: compatibility with code that predates PEP 8, conforming to a\nframework's required names, or when a rule genuinely hurts clarity in context. The\nrule of thumb: **deviate only with a clear readability or compatibility\njustification**, not out of laziness.\n",{"description":61},"Python interview questions on PEP 8, naming conventions, imports and line length, the Zen of Python, formatters and linters like black and ruff, and when it is acceptable to break PEP 8.","python\u002Fidioms\u002Fpep8-style","PEP 8 & Style","XZbVx5iojwhWxTkdsYPJmC4TKVdwn0NbvswTvPh9UZ0",{"id":5278,"title":5279,"body":5280,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":5284,"navigation":66,"order":31,"path":5285,"questions":5286,"related":207,"seo":5311,"seoDescription":5312,"stem":5313,"subtopic":5314,"topic":5315,"topicSlug":5316,"updated":214,"__hash__":5317},"qa\u002Fpython\u002Finternals\u002Fcpython-model.md","Cpython Model",{"type":58,"value":5281,"toc":5282},[],{"title":61,"searchDepth":22,"depth":22,"links":5283},[],{},"\u002Fpython\u002Finternals\u002Fcpython-model",[5287,5291,5295,5299,5303,5307],{"id":5288,"difficulty":84,"q":5289,"a":5290},"source-to-bytecode","How does CPython go from source to running code?","CPython first **compiles** your `.py` source into **bytecode** — a compact,\nplatform-independent instruction set for the Python **virtual machine**. That\nbytecode is then executed by the **interpreter loop** (a big evaluation loop,\nhistorically a giant `switch`), which runs one bytecode instruction at a time.\nCompiled bytecode is cached as **`.pyc`** files in `__pycache__`.\n\n```python\n# mymod.py  ->  compiled to  __pycache__\u002Fmymod.cpython-3xx.pyc\n# The .pyc is reused if the source is unchanged (matched by hash\u002Ftimestamp),\n# so imports skip recompiling. It is NOT machine code — still bytecode.\ndef add(a, b):\n    return a + b\n```\n\nThe key points: bytecode is an **intermediate** representation (not native\nmachine code), `.pyc` is just a **cache** to skip recompilation on import, and the\nVM interprets it at runtime. Rule of thumb: source -> bytecode -> interpreter\nloop, with `.pyc` caching the middle step.\n",{"id":5292,"difficulty":84,"q":5293,"a":5294},"cpython-vs-others","What is CPython, and how does it differ from PyPy and Jython?","**CPython** is the **reference implementation** written in C — it's what you get\nfrom python.org and what most people mean by \"Python.\" The **language** is a\nspec; an **implementation** runs it. Alternatives include **PyPy** (with a\n**JIT** that often runs much faster), **Jython** (runs on the **JVM**), and\n**IronPython** (on **.NET**).\n\n```python\nimport platform\nprint(platform.python_implementation())   # 'CPython', 'PyPy', 'Jython', ...\n```\n\nThey differ in performance and integration: PyPy speeds up long-running pure\nPython via JIT, Jython\u002FIronPython interoperate with Java\u002F.NET libraries, and\nCPython has the widest C-extension ecosystem (NumPy, etc.) plus the **GIL**. Rule\nof thumb: \"Python\" is the language; CPython is the dominant implementation, and\nothers trade ecosystem reach for speed or platform integration.\n",{"id":5296,"difficulty":63,"q":5297,"a":5298},"dis-module","How do you inspect bytecode with the dis module?","The **`dis`** (\"disassemble\") module shows the **bytecode instructions** a\nfunction compiles to — useful for understanding what Python actually does under\nthe hood and for comparing the cost of two approaches.\n\n```python\nimport dis\n\ndef add(a, b):\n    return a + b\n\ndis.dis(add)\n# Example output (abbreviated):\n#   LOAD_FAST   a\n#   LOAD_FAST   b\n#   BINARY_OP   +        # add the two\n#   RETURN_VALUE\n```\n\nEach line is one VM instruction the interpreter loop executes. `dis` is great for\nanswering \"is this comprehension really faster?\" or seeing how the compiler\ndesugars a construct. Rule of thumb: when you want to know what the interpreter\n*literally* runs, disassemble it with `dis`.\n",{"id":5300,"difficulty":84,"q":5301,"a":5302},"frames-call-stack","What are frames and the call stack?","Every time a function is called, CPython creates a **frame object** — a record\nholding that call's **local variables**, the current **instruction pointer**, and\na reference to the caller. Frames are pushed onto the **call stack** as functions\ncall each other and popped as they return. This is the structure a **traceback**\nwalks when printing an error.\n\n```python\nimport inspect\n\ndef inner():\n    frame = inspect.currentframe()\n    print(frame.f_code.co_name)        # 'inner'\n    print(frame.f_back.f_code.co_name) # 'outer' — the caller's frame\n\ndef outer():\n    inner()\n\nouter()\n```\n\nFrames are why each call has **isolated locals** and why exceptions can report the\nfull chain of calls. Deep\u002Finfinite recursion piles up frames until\n`RecursionError` (the stack limit). Rule of thumb: one frame per active call, all\nchained together as the call stack.\n",{"id":5304,"difficulty":63,"q":5305,"a":5306},"compiled-or-interpreted","Is Python compiled or interpreted?","**Both.** Python source is first **compiled** to **bytecode** (a real compilation\nstep), and that bytecode is then **interpreted** by the CPython virtual machine at\nruntime. So the common \"Python is interpreted\" is only half the story — there's a\ncompile phase, just to bytecode rather than to native machine code.\n\n```python\nimport py_compile\npy_compile.compile(\"mymod.py\")   # explicitly produces the .pyc bytecode\n\n# At runtime, the VM's interpreter loop executes that bytecode.\n```\n\nThe distinction that matters: Python compiles to **portable bytecode**, not to\nCPU-specific machine code (the way C does ahead-of-time). PyPy adds a **JIT** that\n*does* compile hot bytecode to machine code at runtime. Rule of thumb: Python is\ncompiled to bytecode and then interpreted.\n",{"id":5308,"difficulty":84,"q":5309,"a":5310},"gil-role","What role does the GIL play in CPython's execution model?","The **GIL** (Global Interpreter Lock) is a single mutex that lets **only one\nthread execute Python bytecode at a time** in a CPython process. The interpreter\nloop holds it while running instructions and periodically releases it (and during\nblocking I\u002FO), so threads take turns rather than running Python code in parallel.\n\n```python\n# Two threads doing CPU-bound Python work do NOT run in parallel:\n# the GIL serializes their bytecode execution on one core.\n# threads -> good for I\u002FO-bound (GIL released during I\u002FO)\n# processes -> needed for CPU-bound parallelism (each has its own GIL)\n```\n\nIt exists largely to make CPython's memory management (reference counting)\nsimpler and C extensions safer. The consequence is that **threads don't give CPU\nparallelism** — that's what multiprocessing is for (see the Concurrency &\nParallelism topic). Rule of thumb: the GIL means one-bytecode-at-a-time per\nprocess, so use processes for CPU-bound parallelism.\n",{"description":61},"Python interview questions on the CPython execution model: source to bytecode to .pyc, the interpreter loop, the dis module, frames and the call stack, and whether Python is compiled or interpreted.","python\u002Finternals\u002Fcpython-model","The CPython Execution Model","Memory & Internals","internals","BTfRbdwE60ns7SueJvUjjVuR4jxN9D_oqBK90FfzmXg",{"id":5319,"title":5320,"body":5321,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":5325,"navigation":66,"order":12,"path":5326,"questions":5327,"related":207,"seo":5352,"seoDescription":5353,"stem":5354,"subtopic":5355,"topic":5315,"topicSlug":5316,"updated":214,"__hash__":5356},"qa\u002Fpython\u002Finternals\u002Fgarbage-collection.md","Garbage Collection",{"type":58,"value":5322,"toc":5323},[],{"title":61,"searchDepth":22,"depth":22,"links":5324},[],{},"\u002Fpython\u002Finternals\u002Fgarbage-collection",[5328,5332,5336,5340,5344,5348],{"id":5329,"difficulty":63,"q":5330,"a":5331},"reference-counting","How does reference counting work in Python?","Every CPython object carries a **reference count** — the number of references\npointing at it. The count goes **up** when you bind a new name, append it to a\ncontainer, or pass it to a function, and **down** when a name is reassigned, goes\nout of scope, or is `del`'d. When the count hits **zero**, the object is\n**immediately deallocated**.\n\n```python\na = [1, 2, 3]    # the list's refcount is 1\nb = a            # 2 — another reference\ndel a            # 1 — still alive (b references it)\nb = None         # 0 — list is freed right away\n```\n\nThis is **deterministic** and prompt — memory is reclaimed the instant the last\nreference disappears, not at some later sweep.\n\nWhy it matters: reference counting handles the vast majority of garbage, but it\n**can't free reference cycles** on its own, which is why CPython adds a second\ncollector.\n",{"id":5333,"difficulty":84,"q":5334,"a":5335},"cyclic-gc","Why does Python need a cyclic garbage collector?","Reference counting fails on **reference cycles** — objects that refer to each other,\nso their counts never reach zero even when nothing outside the cycle reaches them.\nWithout help they'd leak forever. CPython's **cyclic garbage collector** (the `gc`\nmodule) periodically finds and frees these unreachable cycles.\n\n```python\nimport gc\na, b = {}, {}\na['b'] = b        # a -> b\nb['a'] = a        # b -> a   (a cycle)\ndel a, b          # both refcounts stay at 1 — NOT freed by refcounting\ngc.collect()      # the cyclic collector reclaims the unreachable cycle\n```\n\nThe collector works by tracking **container** objects (lists, dicts, instances) and\ndetecting groups whose only references are internal to the group.\n\nRule of thumb: you rarely call `gc.collect()` manually — it runs automatically —\nbut it's worth knowing cycles are collected **later**, not immediately like refcounts.\n",{"id":5337,"difficulty":63,"q":5338,"a":5339},"sys-getrefcount","What does sys.getrefcount tell you and why is it always higher than expected?","`sys.getrefcount(obj)` returns the object's current **reference count**. It almost\nalways reads **one higher** than you expect because **passing the object as the\nargument** creates a temporary reference for the duration of the call.\n\n```python\nimport sys\nx = []\nsys.getrefcount(x)   # 2 — one for `x`, one for the argument itself\n\ny = x\nsys.getrefcount(x)   # 3 — `x`, `y`, and the argument\n```\n\nSmall ints and interned strings show huge counts because they're **cached\nsingletons** shared across the whole interpreter.\n\nWhy it matters: it's a debugging\u002Fteaching tool for understanding aliasing and leaks\n— just remember to **subtract one** for the call's own reference, and don't rely on\nexact values across implementations.\n",{"id":5341,"difficulty":84,"q":5342,"a":5343},"weak-references","What is a weak reference and when do you use one?","A **weak reference** (`weakref` module) points to an object **without increasing its\nreference count**, so it does **not** keep the object alive. When the last *strong*\nreference is gone, the object is collected and the weak reference returns `None`.\n\n```python\nimport weakref\nclass Node: pass\n\nn = Node()\nr = weakref.ref(n)   # weak — doesn't count toward n's lifetime\nr()                  # \u003CNode object> — still alive\ndel n                # last strong ref gone -> object freed\nr()                  # None — referent is dead\n```\n\nThey're ideal for **caches** and **observer\u002Fparent-child back-references** where you\nwant to reference an object but not prevent its cleanup — `weakref.WeakValueDictionary`\nis a common cache type.\n\nRule of thumb: use a weak reference to **break a cycle** or avoid a memory leak when\none object should not own the lifetime of another.\n",{"id":5345,"difficulty":84,"q":5346,"a":5347},"del-pitfalls","What are the pitfalls of the __del__ method?","`__del__` is a **finalizer** called when an object is about to be destroyed — but\nits timing is **not guaranteed**. It runs only when the refcount hits zero (or later,\nvia the cyclic collector), so you can't rely on **when**, or even **whether**, it\nruns. Note `del obj` only decrements the refcount; it doesn't directly call `__del__`.\n\n```python\nclass Resource:\n    def __del__(self):\n        print(\"cleaning up\")   # may run late, or not at all on interpreter exit\n\nr = Resource()\nr2 = r\ndel r                          # nothing happens — r2 still references it\ndel r2                         # NOW refcount is 0 -> __del__ runs\n```\n\nObjects in a reference cycle that define `__del__` historically couldn't be\ncollected at all (improved in Python 3.4+ via PEP 442), and exceptions raised inside\n`__del__` are **ignored**.\n\nRule of thumb: don't use `__del__` for important cleanup — use **context managers\n(`with`)** or `try\u002Ffinally`, which give deterministic, explicit release.\n",{"id":5349,"difficulty":84,"q":5350,"a":5351},"generational-gc","What is generational garbage collection?","The cyclic collector is **generational**: it sorts tracked objects into **three\ngenerations (0, 1, 2)** based on how many collections they've survived. New objects\nstart in **generation 0**, which is scanned **most frequently**; survivors are\n**promoted** to older generations that are scanned **less often**.\n\nThe idea is the **weak generational hypothesis**: most objects die young, so it's\nefficient to focus collection effort on the youngest generation and rarely re-scan\nlong-lived objects.\n\n```python\nimport gc\ngc.get_count()        # (gen0, gen1, gen2) allocation counters\ngc.get_threshold()    # (700, 10, 10) — triggers per generation\ngc.collect(0)         # collect only generation 0 (cheap, frequent)\n```\n\nA generation-0 collection is fast and common; full (generation-2) collections are\nrarer and more expensive.\n\nRule of thumb: this is mostly automatic, but for latency-sensitive code you can tune\nthresholds, call `gc.collect()` strategically, or `gc.disable()` it if you manage\nlifetimes carefully.\n",{"description":61},"Python interview questions on memory management — reference counting, the cyclic garbage collector and reference cycles, sys.getrefcount, weak references, __del__ pitfalls, and generational GC.","python\u002Finternals\u002Fgarbage-collection","Garbage Collection & Reference Counting","FHx3siFM4NKe-jUoUL6tXG3myt5m8Tb5BnZ4L36YsOU",{"id":5358,"title":5359,"body":5360,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5364,"navigation":66,"order":22,"path":5365,"questions":5366,"related":207,"seo":5387,"seoDescription":5388,"stem":5389,"subtopic":5390,"topic":5315,"topicSlug":5316,"updated":214,"__hash__":5391},"qa\u002Fpython\u002Finternals\u002Fidentity-interning.md","Identity Interning",{"type":58,"value":5361,"toc":5362},[],{"title":61,"searchDepth":22,"depth":22,"links":5363},[],{},"\u002Fpython\u002Finternals\u002Fidentity-interning",[5367,5371,5373,5376,5379,5383],{"id":5368,"difficulty":63,"q":5369,"a":5370},"is-vs-equals","What is the difference between is and ==?","**`==`** tests **value equality** — \"do these represent the same data?\" — by\ncalling the object's `__eq__`. **`is`** tests **identity** — \"are these the\n*exact same object* in memory?\" — which is effectively an `id()` comparison. They\nfrequently agree, but conceptually they ask completely different questions.\n\n```python\na = [1, 2, 3]\nb = [1, 2, 3]\na == b      # True  — equal contents\na is b      # False — two distinct list objects\n\nc = a\nc is a      # True  — same object, just another name\n```\n\nUse `==` whenever you care about the **value**, which is almost always. Reserve\n`is` for **identity** checks against singletons. Rule of thumb: if you're\ncomparing data, use `==`; if you're checking \"is this literally that object,\" use\n`is`.\n",{"id":4900,"difficulty":63,"q":4901,"a":5372},"**`id(obj)`** returns a unique integer **identity** for an object that's constant\nfor the object's **lifetime**. In **CPython** it's the object's **memory\naddress**, though that's an implementation detail. Two names with the same `id`\nrefer to the **same object**, and `is` is essentially an `id` comparison.\n\n```python\na = [1, 2]\nb = a\nid(a) == id(b)   # True  — same object\na is b           # True  — equivalent check\n\nc = [1, 2]\nid(a) == id(c)   # False — equal value, different object\n```\n\n`id` is handy for understanding **aliasing** — why mutating through one name\nshows up through another. Don't rely on the actual numeric value (it can be\nreused after an object is garbage-collected); use it only to reason about\nsameness.\n",{"id":4904,"difficulty":63,"q":5374,"a":5375},"What is the small-int cache?","CPython **pre-creates and caches integers from −5 to 256** as singletons at\nstartup. Any time a value in that range is needed, the **same cached object** is\nreused — so equal small ints share identity and `is` returns `True`. Outside that\nwindow, equal integers are typically **distinct** objects.\n\n```python\na = 256\nb = 256\na is b      # True  — both point at the cached 256\n\nc = 257\nd = 257\nc is d      # often False — separate objects\nc == d      # True  — always compare values with ==\n```\n\nThis is purely a **memory\u002Fperformance optimization** and a CPython\nimplementation detail — not a language guarantee. It's the single biggest reason\n`is` \"appears\" to work on numbers. Rule of thumb: never use `is` to compare ints,\nuse `==`.\n",{"id":4908,"difficulty":63,"q":5377,"a":5378},"What is string interning and sys.intern?","**Interning** stores a **single shared copy** of a string so identical strings\ncan be the **same object**, saving memory and making equality checks a fast\npointer comparison. CPython **auto-interns** short, identifier-like string\nliterals (and compile-time constants); other strings may not be. You can force it\nwith **`sys.intern`**.\n\n```python\na = \"hello\"\nb = \"hello\"\na is b           # True  — auto-interned literal\n\nc = \"hello world!\"\nd = \"hello world!\"\nc is d           # often False — not auto-interned\n\nimport sys\ne = sys.intern(\"hello world!\")\nf = sys.intern(\"hello world!\")\ne is f           # True — explicitly interned\n```\n\n`sys.intern` is useful when you compare the **same strings repeatedly** (parsing,\ntokenizing, dict keys) and want the speed\u002Fmemory win. Like int caching, which\nstrings auto-intern is an **implementation detail** — never rely on it for\ncorrectness.\n",{"id":5380,"difficulty":84,"q":5381,"a":5382},"is-coincidental","Why does is sometimes \"work\" coincidentally?","`is` sometimes returns `True` for equal values **only because CPython caches or\ninterns those particular objects** — small ints (−5..256) and many short string\nliterals share one object. It's an accident of optimization, not equality, so it\nbreaks the moment you leave the cached range.\n\n```python\nx = 100\nx is 100         # True  — cached small int (deceiving!)\n\ny = 1000\ny is 1000        # often False — outside the cache\ny == 1000        # True  — the correct comparison\n```\n\nThe danger is that code passes during testing with small values and then fails in\nproduction with larger ones. Treat any `is`-on-a-value that works as a **lucky\ncoincidence**. Rule of thumb: if swapping `is` for `==` would change behavior on\n*some* input, you should have used `==`.\n",{"id":5384,"difficulty":71,"q":5385,"a":5386},"correct-use-of-is","What is the correct use of is?","Use `is` to test **identity against singletons** — objects of which there is\nexactly **one** — most commonly **`None`**, but also `True`, `False`, and your own\n**sentinel** objects. For singletons `is` is correct, fast, and can't be fooled by\na custom `__eq__`.\n\n```python\nif x is None:          # idiomatic, recommended by PEP 8\n    ...\n\n_MISSING = object()    # unique sentinel\ndef get(d, key, default=_MISSING):\n    val = d.get(key, _MISSING)\n    if val is _MISSING:    # distinguishes \"absent\" from \"value is None\"\n        return default\n    return val\n```\n\nA sentinel like `object()` is ideal precisely because `is` checks identity — no\nother object can ever match it. Rule of thumb: `is`\u002F`is not` for `None` and\nsentinels; `==`\u002F`!=` for everything else.\n",{"description":61},"Python interview questions on object identity: is vs ==, the id() function, the small-int cache, string interning, and the correct use of is for None and sentinels.","python\u002Finternals\u002Fidentity-interning","Identity, is vs ==, & Interning","Bxm0c6IuOw0YEDIc513jbfs-3-is_vtYIBOUhOkjzzY",{"id":5393,"title":5394,"body":5395,"description":61,"difficulty":71,"extension":64,"framework":30,"frameworkSlug":28,"meta":5399,"navigation":66,"order":22,"path":5400,"questions":5401,"related":207,"seo":5422,"seoDescription":5423,"stem":5424,"subtopic":5425,"topic":5426,"topicSlug":5427,"updated":214,"__hash__":5428},"qa\u002Fpython\u002Fiteration\u002Fcomprehensions.md","Comprehensions",{"type":58,"value":5396,"toc":5397},[],{"title":61,"searchDepth":22,"depth":22,"links":5398},[],{},"\u002Fpython\u002Fiteration\u002Fcomprehensions",[5402,5406,5410,5414,5418],{"id":5403,"difficulty":71,"q":5404,"a":5405},"list-comp-syntax","What is a list comprehension and why use one?","A **list comprehension** is a concise expression that builds a list in a\nsingle readable line: `[expression for item in iterable]`. It replaces the\ncommon pattern of creating an empty list and `append`-ing in a `for` loop.\n\n```python\n# the verbose way\nsquares = []\nfor n in range(5):\n    squares.append(n * n)\n\n# the comprehension\nsquares = [n * n for n in range(5)]   # [0, 1, 4, 9, 16]\n```\n\nBeyond brevity, comprehensions are usually **faster** than an equivalent\nloop (the iteration runs in optimized C) and they signal intent: \"I'm\ntransforming a sequence into a new list.\" Reach for one whenever you're\nbuilding a list by mapping or filtering another iterable.\n",{"id":5407,"difficulty":71,"q":5408,"a":5409},"comp-filtering","How do you filter and conditionally transform inside a comprehension?","A trailing **`if` clause filters** items — only elements for which it is\ntruthy are kept. A **conditional expression** (`x if cond else y`) goes at\nthe **front**, before the `for`, because it's part of the output expression,\nnot a filter.\n\n```python\nnums = range(6)\n\nevens = [n for n in nums if n % 2 == 0]          # filter: [0, 2, 4]\nlabels = [\"even\" if n % 2 == 0 else \"odd\"        # transform every item\n          for n in nums]                         # ['even','odd',...]\nboth = [n * 2 for n in nums if n > 2]            # filter THEN transform\n```\n\nRemember the position rule: a **filter `if`** comes after the `for`; a\n**`if\u002Felse` expression** comes before it. Mixing them up is a common\nbeginner error.\n",{"id":5411,"difficulty":63,"q":5412,"a":5413},"nested-comp","How do nested comprehensions work?","You can chain multiple `for` clauses to flatten or iterate over nested\ndata. The clauses read **left to right in the same order** as nested\nloops. You can also nest a comprehension *inside* the output expression to\nbuild a list of lists.\n\n```python\nmatrix = [[1, 2], [3, 4]]\n\nflat = [x for row in matrix for x in row]   # [1, 2, 3, 4]\n# equivalent to:\n#   for row in matrix:\n#       for x in row:\n\ngrid = [[r * c for c in range(3)] for r in range(3)]  # list of rows\n```\n\nThe trap is reading the order backwards — the **outer** loop is written\nfirst. Keep nesting shallow; two levels is usually the readability limit\nbefore a plain loop is clearer.\n",{"id":5415,"difficulty":71,"q":5416,"a":5417},"dict-set-comp","What are dict and set comprehensions?","The same syntax works for dicts and sets. A **dict comprehension** uses\n`{key: value for ...}` and a **set comprehension** uses `{expr for ...}`\n(no colon). Sets automatically deduplicate results.\n\n```python\nnames = [\"ada\", \"grace\", \"ada\"]\n\nlengths = {n: len(n) for n in names}     # {'ada': 3, 'grace': 5}\nunique  = {n for n in names}             # {'ada', 'grace'}  (deduped)\nswapped = {v: k for k, v in lengths.items()}  # invert a dict\n```\n\nNote `{}` alone is an empty **dict**, not a set — use `set()` for an empty\nset. Dict and set comprehensions accept the same `if` filters and nested\n`for` clauses as list comprehensions.\n",{"id":5419,"difficulty":63,"q":5420,"a":5421},"comp-vs-map-filter","When should you NOT use a comprehension?","Comprehensions are for **building a collection**. Avoid them when you only\nwant **side effects** (printing, writing to a DB) — that abuse hides intent\nand builds a throwaway list. Use a plain `for` loop instead. Also skip them\nwhen the logic is so complex that the line becomes unreadable.\n\n```python\n# bad: comprehension purely for side effects\n[print(x) for x in items]      # builds a useless list of Nones\n\n# good: a loop says \"do this for each\"\nfor x in items:\n    print(x)\n```\n\nComprehensions overlap with `map`\u002F`filter`, but are usually more readable\nand avoid `lambda`. Prefer a generator expression `(...)` over a list comp\nwhen you only iterate once and don't need to materialize the whole result.\n",{"description":61},"Python interview questions on list, dict, and set comprehensions, filtering with if, conditional expressions, nested comprehensions, and when not to use them.","python\u002Fiteration\u002Fcomprehensions","List, Dict & Set Comprehensions","Comprehensions & Iteration","iteration","uGKkZQVAIauWnty3ubl1uoueazHZ0xd5yzGpbq2r5x4",{"id":5430,"title":5431,"body":5432,"description":61,"difficulty":71,"extension":64,"framework":30,"frameworkSlug":28,"meta":5436,"navigation":66,"order":40,"path":5437,"questions":5438,"related":207,"seo":5459,"seoDescription":5460,"stem":5461,"subtopic":5462,"topic":5426,"topicSlug":5427,"updated":214,"__hash__":5463},"qa\u002Fpython\u002Fiteration\u002Fenumerate-zip.md","Enumerate Zip",{"type":58,"value":5433,"toc":5434},[],{"title":61,"searchDepth":22,"depth":22,"links":5435},[],{},"\u002Fpython\u002Fiteration\u002Fenumerate-zip",[5439,5443,5447,5451,5455],{"id":5440,"difficulty":71,"q":5441,"a":5442},"enumerate-basics","What does enumerate do and how do you set its start?","`enumerate(iterable)` pairs each item with a running **index**, yielding\n`(index, value)` tuples. It saves you from the error-prone manual counter\nor `range(len(...))` pattern. The optional **`start`** argument sets the\nfirst index (default `0`).\n\n```python\ncolors = [\"red\", \"green\", \"blue\"]\n\nfor i, c in enumerate(colors):\n    print(i, c)            # 0 red \u002F 1 green \u002F 2 blue\n\nfor rank, c in enumerate(colors, start=1):\n    print(rank, c)         # 1 red \u002F 2 green \u002F 3 blue\n```\n\nPrefer `enumerate` over `range(len(seq))` whenever you need both the index\nand the item — it's more readable and works on any iterable, not just\nindexable sequences.\n",{"id":5444,"difficulty":71,"q":5445,"a":5446},"zip-basics","What does zip do and how does zip_longest differ?","`zip(a, b, ...)` walks several iterables **in parallel**, yielding tuples of\naligned elements. It stops at the **shortest** input, silently dropping\nextras. `itertools.zip_longest` instead runs to the **longest**, filling\nmissing slots with a `fillvalue`.\n\n```python\nnames = [\"ada\", \"grace\", \"edsger\"]\nages  = [36, 45]\n\nlist(zip(names, ages))     # [('ada', 36), ('grace', 45)]  — 'edsger' dropped\n\nfrom itertools import zip_longest\nlist(zip_longest(names, ages, fillvalue=0))\n# [('ada', 36), ('grace', 45), ('edsger', 0)]\n```\n\nUse plain `zip` when lengths match (or truncation is intended); reach for\n`zip_longest` when you must not lose data from the longer iterable.\n",{"id":5448,"difficulty":63,"q":5449,"a":5450},"unzip-with-star","How do you unzip a list of pairs with zip(*)?","`zip` is its own inverse. Applying `zip(*pairs)` **unpacks** the list of\ntuples as separate arguments, so `zip` re-groups them column-wise —\neffectively transposing rows into columns.\n\n```python\npairs = [(\"ada\", 36), (\"grace\", 45)]\n\nnames, ages = zip(*pairs)\nnames    # ('ada', 'grace')\nages     # (36, 45)\n```\n\nThis also transposes a matrix: `list(zip(*matrix))`. Note the results are\n**tuples**, not lists, and the input is consumed if it's an iterator — wrap\nin `list(...)` if you need list results.\n",{"id":5452,"difficulty":71,"q":5453,"a":5454},"extended-unpacking","How does extended (star) unpacking work?","A starred target in an assignment captures **\"the rest\"** as a list. You can\nplace `*name` at the start, middle, or end, and the non-starred names take\nfixed positions — Python figures out the split.\n\n```python\nfirst, *rest = [1, 2, 3, 4]      # first=1, rest=[2, 3, 4]\n*init, last = [1, 2, 3, 4]       # init=[1, 2, 3], last=4\nhead, *mid, tail = [1, 2, 3, 4]  # head=1, mid=[2, 3], tail=4\n```\n\nExactly **one** starred target is allowed per assignment, and it always\nbecomes a `list` (even if empty). This is cleaner than slicing for grabbing\nthe head\u002Ftail of a sequence.\n",{"id":5456,"difficulty":63,"q":5457,"a":5458},"zip-dict-star-args","How do you build a dict from zip and pass star-args in a call?","Pairing two sequences with `zip` and feeding them to `dict()` is the\nidiomatic way to build a mapping. The `*` and `**` operators also unpack\niterables\u002Fdicts **into function calls** as positional and keyword\narguments.\n\n```python\nkeys = [\"x\", \"y\", \"z\"]\nvals = [1, 2, 3]\nd = dict(zip(keys, vals))        # {'x': 1, 'y': 2, 'z': 3}\n\ndef point(x, y, z): return (x, y, z)\nargs = [1, 2, 3]\npoint(*args)                     # unpack list -> positional\npoint(**d)                       # unpack dict -> keyword args\n```\n\nUse `*` to spread a sequence into positional parameters and `**` to spread a\ndict into keyword parameters — the call-site mirror of `*args`\u002F`**kwargs` in\na function signature.\n",{"description":61},"Python interview questions on enumerate with start, zip and zip_longest, unzipping with zip(*), extended iterable unpacking, and star-args at the call site.","python\u002Fiteration\u002Fenumerate-zip","enumerate, zip & Unpacking","dlhdQ8WjRw-HuDrX9oGDff8YDeOxNvXA1W7WGXQzGkY",{"id":5465,"title":5466,"body":5467,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5471,"navigation":66,"order":12,"path":5472,"questions":5473,"related":207,"seo":5494,"seoDescription":5495,"stem":5496,"subtopic":5497,"topic":5426,"topicSlug":5427,"updated":214,"__hash__":5498},"qa\u002Fpython\u002Fiteration\u002Fgenerators.md","Generators",{"type":58,"value":5468,"toc":5469},[],{"title":61,"searchDepth":22,"depth":22,"links":5470},[],{},"\u002Fpython\u002Fiteration\u002Fgenerators",[5474,5478,5482,5486,5490],{"id":5475,"difficulty":71,"q":5476,"a":5477},"what-is-generator","What is a generator and what does the yield keyword do?","A **generator** is a function that produces a **lazy sequence** of values one at\na time. Any function containing **`yield`** becomes a generator function: calling\nit doesn't run the body — it returns a **generator object** (an iterator). Each\ntime you call `next()` (or iterate), the body runs until the next `yield`, hands\nback that value, and **pauses**, preserving all local state.\n\n```python\ndef counter():\n    print(\"start\")\n    yield 1\n    yield 2          # execution pauses here between next() calls\n    yield 3\n\ng = counter()        # nothing printed yet — body hasn't run\nnext(g)              # prints \"start\", returns 1\nnext(g)              # returns 2 (resumes after first yield)\n```\n\nWhen the function returns (or falls off the end), a **`StopIteration`** is\nraised to signal exhaustion. Generators are the simplest way to write a custom\n**iterator** without manually implementing `__iter__`\u002F`__next__`.\n",{"id":5479,"difficulty":63,"q":5480,"a":5481},"generator-vs-list-memory","How does a generator save memory compared to a list?","A list **materializes every element in memory at once**, so its footprint grows\nwith the number of items. A generator holds only its **current state** and\ncomputes each value **on demand**, so its memory use is roughly **constant**\nregardless of how many values it ultimately yields.\n\n```python\nimport sys\nnums = [n * n for n in range(1_000_000)]   # ~8 MB list, built eagerly\ngen  = (n * n for n in range(1_000_000))   # lazy — tiny, fixed size\n\nsys.getsizeof(nums)   # large\nsys.getsizeof(gen)    # ~100 bytes, regardless of range\n```\n\nThis makes generators ideal for **large or streaming data** — reading a\nmulti-gigabyte file line by line, or a pipeline of transformations — where you'd\nnever want the whole dataset in RAM. The trade-off: you can only iterate a\ngenerator **once**, and you can't index or `len()` it.\n",{"id":5483,"difficulty":63,"q":5484,"a":5485},"genexp-vs-listcomp","What is the difference between a generator expression and a list comprehension?","They share syntax but differ in their brackets and behaviour. A **list\ncomprehension** uses `[...]` and builds the **entire list eagerly**. A\n**generator expression** uses `(...)` and produces a **lazy iterator** that\nyields values one at a time, computing nothing until consumed.\n\n```python\nlc = [x * 2 for x in range(5)]   # [0, 2, 4, 6, 8] — built now\nge = (x * 2 for x in range(5))   # \u003Cgenerator object> — built on demand\n\n# parentheses are optional when it's the sole argument:\ntotal = sum(x * 2 for x in range(5))   # streams — no temp list\n```\n\nPrefer a **generator expression** when feeding an aggregator like `sum`, `max`,\n`any`, or `join` over a large source — it avoids creating a throwaway list. Use a\n**list comprehension** when you need the full result repeatedly, want to index\nit, or need `len()`.\n",{"id":5487,"difficulty":63,"q":5488,"a":5489},"yield-from","What does yield from do?","**`yield from \u003Citerable>`** **delegates** to a sub-iterator: it yields every\nvalue from the iterable as if you'd written a loop of `yield`s, but also\ntransparently forwards **`send`**, **`throw`**, and the sub-generator's\n**return value**. It's the clean way to **compose** or **flatten** generators.\n\n```python\ndef chain(*iterables):\n    for it in iterables:\n        yield from it          # vs: for x in it: yield x\n\nlist(chain([1, 2], (3, 4)))    # [1, 2, 3, 4]\n\ndef sub():\n    yield 1\n    return 99                  # captured by the delegator\ndef main():\n    result = yield from sub()  # result == 99\n```\n\nBeyond saving a loop, `yield from` is what makes generator **delegation** and\ncoroutine composition possible. Rule of thumb: use it whenever you want one\ngenerator to **fully drain another**.\n",{"id":5491,"difficulty":84,"q":5492,"a":5493},"infinite-generators","How can a generator be infinite, and why doesn't it hang?","Because generators are **lazy**, the body only advances when a value is\nrequested — so an **unbounded loop** is fine: it never tries to produce all\nvalues at once. You control termination from the **consumer** side, by stopping\niteration whenever you've taken enough.\n\n```python\ndef naturals():\n    n = 0\n    while True:        # infinite — but harmless\n        yield n\n        n += 1\n\nfrom itertools import islice\nlist(islice(naturals(), 5))   # [0, 1, 2, 3, 4] — take just 5\n```\n\nThis underpins `itertools.count`, `cycle`, and `repeat`, and lets you model\nstreams elegantly. The danger is forgetting to bound the consumer:\n`list(naturals())` or `for x in naturals(): print(x)` **will** run forever — pair\ninfinite generators with `islice`, a `break`, or `takewhile`.\n",{"description":61},"Python interview questions on generators and yield, lazy evaluation, generator expressions vs list comprehensions, yield from, and infinite generators.","python\u002Fiteration\u002Fgenerators","Generators & yield","8cOk8zKE2hYNCWFPkpf54--NW0VVil4L10uT-XTtKR0",{"id":5500,"title":5501,"body":5502,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5506,"navigation":66,"order":31,"path":5507,"questions":5508,"related":207,"seo":5533,"seoDescription":5534,"stem":5535,"subtopic":5536,"topic":5426,"topicSlug":5427,"updated":214,"__hash__":5537},"qa\u002Fpython\u002Fiteration\u002Fiterators.md","Iterators",{"type":58,"value":5503,"toc":5504},[],{"title":61,"searchDepth":22,"depth":22,"links":5505},[],{},"\u002Fpython\u002Fiteration\u002Fiterators",[5509,5513,5517,5521,5525,5529],{"id":5510,"difficulty":63,"q":5511,"a":5512},"iterable-vs-iterator","What is the difference between an iterable and an iterator?","An **iterable** is anything you can loop over — it knows how to produce an\niterator via `__iter__`. An **iterator** is the object that actually does\nthe walking: it has `__next__` and yields one value at a time, remembering\nits position. Every iterator is iterable (its `__iter__` returns itself),\nbut not every iterable is an iterator.\n\n```python\nnums = [1, 2, 3]          # list: iterable, NOT an iterator\nit = iter(nums)           # iterator over the list\nnext(it)                  # 1  — iterators track position\nnext(it)                  # 2\n```\n\nThink of the iterable as the *collection* and the iterator as a\n*cursor\u002Fbookmark* into it. You can create many independent iterators from\none iterable.\n",{"id":5514,"difficulty":63,"q":5515,"a":5516},"iter-next-protocol","What methods make up the iterator protocol?","The **iterator protocol** is two methods. `__iter__` must return the\niterator object itself, and `__next__` returns the next value or raises\n**`StopIteration`** when exhausted. That exception is the agreed signal\nthat there are no more items.\n\n```python\nit = iter([10, 20])\nit.__next__()      # 10\nit.__next__()      # 20\nit.__next__()      # raises StopIteration\n```\n\nAn **iterable** only needs `__iter__` (returning a fresh iterator). An\n**iterator** needs both. The `StopIteration` raise is what lets `for` loops\nknow when to stop — they catch it silently.\n",{"id":5518,"difficulty":71,"q":5519,"a":5520},"iter-next-builtins","What do the built-in iter() and next() functions do?","`iter(obj)` calls `obj.__iter__()` to get an iterator; `next(it)` calls\n`it.__next__()` to advance it. `next()` accepts an optional **default** that\nis returned instead of raising `StopIteration` when the iterator is\nexhausted — handy for safe peeking.\n\n```python\nit = iter(\"ab\")\nnext(it)            # 'a'\nnext(it)            # 'b'\nnext(it, \"done\")    # 'done'  — default instead of StopIteration\n\n# iter() also has a two-arg sentinel form:\n# iter(callable, sentinel) calls until it returns sentinel\n```\n\nUse the default argument whenever you want to drain or sample an iterator\nwithout wrapping `next()` in a `try`\u002F`except StopIteration`.\n",{"id":5522,"difficulty":63,"q":5523,"a":5524},"custom-iterator-class","How do you build a custom iterator class?","Implement `__iter__` (return `self`) and `__next__` (return the next value\nor raise `StopIteration`). The instance holds its own state between calls.\n\n```python\nclass Countdown:\n    def __init__(self, start):\n        self.n = start\n    def __iter__(self):\n        return self\n    def __next__(self):\n        if self.n \u003C= 0:\n            raise StopIteration\n        self.n -= 1\n        return self.n + 1\n\nlist(Countdown(3))     # [3, 2, 1]\n```\n\nThis works, but for most cases a **generator function** (using `yield`) is\nfar less boilerplate — it builds the `__iter__`\u002F`__next__`\u002F`StopIteration`\nmachinery for you. Reach for a class only when you need extra methods or\nexplicit state.\n",{"id":5526,"difficulty":84,"q":5527,"a":5528},"for-under-the-hood","How does a for loop work under the hood?","A `for` loop is sugar over the iterator protocol. Python calls `iter()` on\nthe iterable once to get an iterator, then repeatedly calls `next()` on it,\nbinding each result to the loop variable, until `StopIteration` is raised —\nwhich it catches to end the loop.\n\n```python\nfor x in [1, 2, 3]:\n    print(x)\n\n# is roughly equivalent to:\n_it = iter([1, 2, 3])\nwhile True:\n    try:\n        x = next(_it)\n    except StopIteration:\n        break\n    print(x)\n```\n\nThis is why any object implementing the protocol \"just works\" in a `for`\nloop, comprehension, or `*`-unpacking. The `StopIteration` is the hidden\nhandshake that terminates the loop.\n",{"id":5530,"difficulty":63,"q":5531,"a":5532},"iterator-exhaustion","Why can you only iterate an iterator once?","An iterator is **single-use \u002F exhaustible**: once `__next__` has walked to\nthe end and raised `StopIteration`, it stays exhausted — there is no reset.\nRe-iterating yields nothing. This trips people up with generators and\n`zip`\u002F`map` objects.\n\n```python\nit = iter([1, 2, 3])\nlist(it)     # [1, 2, 3]\nlist(it)     # []  — already exhausted!\n\ngen = (x for x in range(3))\nsum(gen)     # 3\nsum(gen)     # 0  — the generator is spent\n```\n\nA **list** (an iterable, not an iterator) can be looped many times because\neach loop calls `iter()` to get a *fresh* iterator. If you need to reuse an\nexhaustible result, materialize it into a list first.\n",{"description":61},"Python interview questions on iterables vs iterators, the iterator protocol, __iter__ and __next__, StopIteration, building custom iterators, and how for loops work under the hood.","python\u002Fiteration\u002Fiterators","Iterators & the Iterator Protocol","MDIPCY-D1tLVqU5RVp-SI3ZbPEO4RflTJJO17wGSu24",{"id":5539,"title":5540,"body":5541,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5545,"navigation":66,"order":12,"path":5546,"questions":5547,"related":207,"seo":5568,"seoDescription":5569,"stem":5570,"subtopic":5571,"topic":5572,"topicSlug":5573,"updated":214,"__hash__":5574},"qa\u002Fpython\u002Fmodules\u002Fimports.md","Imports",{"type":58,"value":5542,"toc":5543},[],{"title":61,"searchDepth":22,"depth":22,"links":5544},[],{},"\u002Fpython\u002Fmodules\u002Fimports",[5548,5552,5556,5560,5564],{"id":5549,"difficulty":71,"q":5550,"a":5551},"module-vs-package","What is the difference between a module and a package?","A **module** is a single `.py` file — a namespace of functions, classes, and\nvariables you can `import`. A **package** is a **directory of modules**; it\ngroups related modules under one dotted namespace (`mypkg.utils`).\n\nHistorically a package needed an `__init__.py` file to be recognized; that file\nruns when the package is first imported and can expose a curated public API.\nSince Python 3.3, a directory without `__init__.py` can still be a **namespace\npackage**, but a regular package with `__init__.py` is the common, explicit choice.\n\n```python\n# file layout\n# mypkg\u002F\n#   __init__.py      \u003C- makes it a regular package\n#   utils.py         \u003C- a module inside the package\n\nimport mypkg.utils          # import a module from a package\nfrom mypkg import utils     # same module, bound as `utils`\n```\n\nWhy it matters: modules are the **unit of code reuse**, packages are the **unit of\norganization** — both are objects at runtime (`module.__file__`, `package.__path__`).\n",{"id":5553,"difficulty":63,"q":5554,"a":5555},"absolute-vs-relative-imports","What is the difference between absolute and relative imports?","An **absolute import** spells out the full path from a top-level package\n(`from mypkg.utils import helper`). A **relative import** uses leading dots to\nnavigate relative to the **current module's package** — one dot for the current\npackage, two for the parent.\n\n```python\n# inside mypkg\u002Fsub\u002Fthing.py\nfrom mypkg.utils import helper   # absolute — explicit, unambiguous\nfrom ..utils import helper       # relative — '..' = mypkg, then .utils\nfrom . import sibling            # relative — same package\n```\n\nRelative imports only work **inside a package** and only when the module is run as\npart of that package — running the file directly with `python thing.py` breaks them\n(`ImportError: attempted relative import with no known parent package`).\n\nRule of thumb: PEP 8 **prefers absolute imports** for clarity; reach for relative\nimports inside large packages to avoid repeating a long package prefix.\n",{"id":5557,"difficulty":71,"q":5558,"a":5559},"name-main","What does `if __name__ == \"__main__\"` do?","Every module has a `__name__` variable. When a file is **run directly**, Python\nsets its `__name__` to the string `\"__main__\"`. When the same file is **imported**,\n`__name__` is set to the **module's name** instead. The guard therefore runs code\n**only when the file is executed as a script**, not when it's imported.\n\n```python\ndef main():\n    print(\"running as a program\")\n\nif __name__ == \"__main__\":   # True only via `python myfile.py`\n    main()                   # skipped when `import myfile`\n```\n\nThis lets a file double as both an importable library and a runnable program: tests\nand other modules can import its functions without triggering the script logic.\n\nRule of thumb: put **executable entry-point code** under the guard so importing the\nmodule stays free of side effects.\n",{"id":5561,"difficulty":63,"q":5562,"a":5563},"sys-path-resolution","How does Python find the module you import?","On `import x`, Python searches a list of **finders** and, for file-based modules,\nwalks **`sys.path`** — a list of directories — in order, using the **first match**.\n`sys.path` is built from the script's directory (or cwd), the `PYTHONPATH`\nenvironment variable, and the installation's standard library \u002F `site-packages`.\n\n```python\nimport sys\nprint(sys.path)        # ['', '\u002Fusr\u002Flib\u002Fpython3.12', '...\u002Fsite-packages', ...]\n# '' (or the script dir) is searched first — local files can SHADOW stdlib!\n\n# a file named random.py in your folder will hide the real `random` module\n```\n\nBuilt-in modules and frozen modules are found before `sys.path` is consulted, which\nis why you can't shadow `sys` itself.\n\nWhy it matters: a local file named like a stdlib module (`queue.py`, `email.py`)\nsilently **shadows** the real one — a classic, confusing import bug.\n",{"id":5565,"difficulty":84,"q":5566,"a":5567},"import-caching-circular","What is `sys.modules` and how does it relate to circular imports?","`sys.modules` is a **cache** mapping module names to already-imported module\nobjects. The **first** import of a module executes its code top to bottom and stores\nthe result there; every later `import` of the same name just returns the cached\nobject — so module code runs **once** per interpreter session.\n\nA **circular import** is when module A imports B while B imports A. Because the\nimporting module is added to `sys.modules` **before** its body finishes running, the\nsecond import gets a **partially-initialized** module — names defined later in the\nfile aren't there yet.\n\n```python\n# a.py\nimport b                 # starts importing b...\ndef helper(): ...\n\n# b.py\nimport a                 # a is in sys.modules but only HALF-defined\nprint(a.helper)          # AttributeError — helper isn't bound yet\n```\n\nFixes: **move the import inside the function** that needs it (deferred until call\ntime), restructure to remove the cycle, or import the module object rather than\nnames from it. Rule of thumb: circular imports usually signal that two modules\nshould share a third.\n",{"description":61},"Python interview questions on the import system — modules vs packages, absolute vs relative imports, __main__, sys.path module resolution, import caching, and circular imports.","python\u002Fmodules\u002Fimports","The Import System","Modules, Packages & Environments","modules","jtJSf_YAtyPZXIz_7UFkHQ6ZwMS6wa_500IBOxpfjag",{"id":5576,"title":5577,"body":5578,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5582,"navigation":66,"order":22,"path":5583,"questions":5584,"related":207,"seo":5605,"seoDescription":5606,"stem":5607,"subtopic":5608,"topic":5572,"topicSlug":5573,"updated":214,"__hash__":5609},"qa\u002Fpython\u002Fmodules\u002Fpackages.md","Packages",{"type":58,"value":5579,"toc":5580},[],{"title":61,"searchDepth":22,"depth":22,"links":5581},[],{},"\u002Fpython\u002Fmodules\u002Fpackages",[5585,5589,5593,5597,5601],{"id":5586,"difficulty":71,"q":5587,"a":5588},"package-vs-module","What is the difference between a module and a package, and what does __init__.py do?","A **module** is a single `.py` file. A **package** is a **directory** of modules\nthat you import as a unit, traditionally marked by an **`__init__.py`** file. That\nfile runs when the package is first imported, so it's where you can set the\npackage's public API or do setup; it's often empty, which is fine.\n\n```python\n# myapp\u002F                 \u003C- package\n#   __init__.py          \u003C- marks it a package, runs on import\n#   db.py                \u003C- module\n#   utils\u002F               \u003C- subpackage\n#       __init__.py\n#       text.py\n\nimport myapp.db                 # import a module from the package\nfrom myapp.utils.text import slug\n```\n\nA common use of `__init__.py` is to **re-export** so callers can write\n`from myapp import db` cleanly. Modules organize code into files; packages organize\nmodules into a namespace tree.\n",{"id":5590,"difficulty":63,"q":5591,"a":5592},"python-m-main","What do `python -m` and __main__.py do?","**`python -m pkg.module`** runs a module **as a script** while still locating it via\nthe import system (so relative imports and the package context work). When you point\n`-m` at a **package**, Python runs that package's **`__main__.py`** — that's how a\npackage becomes executable, like `python -m http.server`.\n\n```bash\npython -m http.server 8000     # runs http.server's __main__.py\npython -m myapp                # runs myapp\u002F__main__.py\npython -m pytest               # run an installed tool as a module\n```\n\n```python\n# myapp\u002F__main__.py\nfrom myapp.cli import main\nmain()\n```\n\nUse `-m` to run installed\u002Fpackaged code by its import name rather than a file path,\nwhich avoids the `sys.path` surprises you get from running a file directly.\n",{"id":5594,"difficulty":63,"q":5595,"a":5596},"dunder-all","What does __all__ control?","`__all__` is a list of names that defines a module's (or package's) **public API for\nwildcard imports** — `from module import *` imports exactly those names. Without it,\n`import *` grabs every name not starting with an underscore.\n\n```python\n# mymath.py\n__all__ = [\"add\", \"PI\"]      # only these are exported by *\n\ndef add(a, b): return a + b\ndef _helper(): ...           # private anyway\nPI = 3.14159\n\n# elsewhere\nfrom mymath import *         # gets add and PI only\n```\n\nIt does **not** prevent explicit imports (`from mymath import _helper` still works)\n— it only curates `*` and documents intent. Define `__all__` to keep `import *`\nclean and to signal what's officially public.\n",{"id":5598,"difficulty":84,"q":5599,"a":5600},"namespace-packages","What is a namespace package?","A **namespace package** (PEP 420) is a package with **no `__init__.py`** whose\ncontents can be **split across multiple directories** on `sys.path`. Python merges\nthose directories into one logical package — useful for plugins where different\ndistributions contribute to a shared top-level namespace.\n\n```python\n# path1\u002Facme\u002Ffoo.py\n# path2\u002Facme\u002Fbar.py     (no __init__.py in either acme\u002F)\n# with both paths on sys.path:\nimport acme.foo\nimport acme.bar          # both resolve under the merged 'acme' namespace\n```\n\nSince Python 3.3, a directory **without** `__init__.py` can still be importable as a\nnamespace package. For an ordinary single-location package you usually still want a\nregular package (with `__init__.py`); reserve namespace packages for splitting a\nnamespace across separately-installed parts.\n",{"id":5602,"difficulty":63,"q":5603,"a":5604},"script-vs-import","What is the difference between running a file and importing it?","When you **run** a file (`python foo.py`), Python sets its `__name__` to\n**`\"__main__\"`**. When you **import** it, `__name__` is the **module's name**. The\n`if __name__ == \"__main__\":` guard uses this so a file can act as both a runnable\nscript and an importable library — the guarded code runs only on direct execution.\n\n```python\n# greet.py\ndef hello(name): return f\"Hi {name}\"\n\nif __name__ == \"__main__\":   # runs only via `python greet.py`\n    print(hello(\"world\"))    # NOT run when `import greet`\n```\n\nWithout the guard, your script's top-level side effects (running, printing, parsing\nargs) would fire **every time the module is imported**. Always put script entry\npoints behind the `__main__` guard.\n",{"description":61},"Python interview questions on packages vs modules, the role of __init__.py, python -m and __main__.py, __all__, namespace packages, and running a script versus importing it.","python\u002Fmodules\u002Fpackages","Packages & __main__","UrCSSzH8UD9IVaDM_gcmPtivyFD05XPsmRvHMSFzpps",{"id":5611,"title":5612,"body":5613,"description":61,"difficulty":71,"extension":64,"framework":30,"frameworkSlug":28,"meta":5617,"navigation":66,"order":31,"path":5618,"questions":5619,"related":207,"seo":5644,"seoDescription":5645,"stem":5646,"subtopic":5647,"topic":5572,"topicSlug":5573,"updated":214,"__hash__":5648},"qa\u002Fpython\u002Fmodules\u002Fvirtual-environments.md","Virtual Environments",{"type":58,"value":5614,"toc":5615},[],{"title":61,"searchDepth":22,"depth":22,"links":5616},[],{},"\u002Fpython\u002Fmodules\u002Fvirtual-environments",[5620,5624,5628,5632,5636,5640],{"id":5621,"difficulty":71,"q":5622,"a":5623},"what-is-venv","What is a virtual environment and why does isolation matter?","A **virtual environment** is a self-contained directory with its own Python\ninterpreter and its own `site-packages`, so each project gets an **isolated** set of\ndependencies. Isolation matters because two projects often need **different\nversions** of the same package — without venvs, installing for one breaks the other,\nand installing globally can even break system tools.\n\n```bash\n# Project A needs Django 3, Project B needs Django 5.\n# Separate venvs let both coexist without conflict.\npython -m venv .venv        # creates an isolated environment\n```\n\nA venv keeps dependencies **per project** and out of the global interpreter, making\nbuilds reproducible and avoiding \"works on my machine\" version clashes. Use one for\nevery project.\n",{"id":5625,"difficulty":71,"q":5626,"a":5627},"create-activate","How do you create and activate a virtual environment?","Create one with the standard-library **`venv`** module, then **activate** it so the\nshell uses the venv's `python` and `pip`. The activation command differs by OS;\n**`deactivate`** returns to the global interpreter.\n\n```bash\npython -m venv .venv            # create (folder named .venv)\n\nsource .venv\u002Fbin\u002Factivate       # activate on macOS \u002F Linux\n.venv\\Scripts\\activate          # activate on Windows\n\nwhich python                    # -> ...\u002F.venv\u002Fbin\u002Fpython while active\ndeactivate                      # leave the venv\n```\n\nOnce active, `pip install` puts packages **inside** the venv only. Add `.venv\u002F` to\n`.gitignore` — you commit the dependency list, not the environment itself.\n",{"id":5629,"difficulty":71,"q":5630,"a":5631},"pip-requirements","How do you install packages and what is requirements.txt?","**`pip install`** fetches packages from PyPI into the active environment. A\n**`requirements.txt`** lists a project's dependencies (often with pinned versions)\nso anyone can recreate the same environment with one command.\n\n```bash\npip install requests            # install latest\npip install \"requests==2.31.0\"  # install a specific version\n\npip install -r requirements.txt # install everything listed in the file\n```\n\n```text\n# requirements.txt\nrequests==2.31.0\nrich>=13.0\n```\n\nCommitting `requirements.txt` makes installs **reproducible** across machines and\nCI. Install into an **activated venv**, never globally with `sudo pip`.\n",{"id":5633,"difficulty":63,"q":5634,"a":5635},"pip-freeze","What does pip freeze do?","`pip freeze` prints every installed package with its **exact pinned version** in\n`requirements.txt` format, so you can capture the current environment. Redirect it\nto a file to snapshot dependencies.\n\n```bash\npip freeze                          # list installed pkgs == versions\npip freeze > requirements.txt       # snapshot the current environment\npip list                            # similar, but human-readable table\n```\n\nA caveat: `pip freeze` records **everything installed, including transitive\ndependencies**, which can make the file noisy. Many teams instead hand-curate\ndirect dependencies (or use a lock-file tool) and keep `pip freeze` for capturing a\nknown-good full snapshot.\n",{"id":5637,"difficulty":63,"q":5638,"a":5639},"editable-install","What is an editable install (`pip install -e`)?","An **editable install** links your project into the environment **in place** instead\nof copying it, so edits to the source take effect **immediately** without\nreinstalling. It's the standard way to work on a package you're developing locally.\n\n```bash\npip install -e .                # install the current project, editable\npip install -e \".[dev]\"         # editable + optional 'dev' extras\n```\n\nBecause the install points at your working tree, changing the code updates the\nimported package right away — no rebuild needed. Use `-e` for **your own package\nunder development**, and a normal `pip install` for third-party dependencies.\n",{"id":5641,"difficulty":63,"q":5642,"a":5643},"pyproject-toml","What is pyproject.toml?","`pyproject.toml` is the **modern, standardized** config file (PEP 518\u002F621) for a\nPython project — it declares the **build system**, project **metadata**, and\n**dependencies** in one place, replacing the older `setup.py`\u002F`setup.cfg` split. Most\nmodern tools (build, pip, linters, formatters) read it.\n\n```toml\n[project]\nname = \"myapp\"\nversion = \"0.1.0\"\ndependencies = [\"requests>=2.31\", \"rich\"]\n\n[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n```\n\nWith dependencies declared here, `pip install .` (or `-e .`) reads them directly, so\na separate `requirements.txt` becomes optional. It's the recommended starting point\nfor any new packaged project.\n",{"description":61},"Python interview questions on virtual environments and pip — what a venv is and why isolation matters, creating and activating one, requirements.txt, pip freeze, editable installs, and pyproject.toml.","python\u002Fmodules\u002Fvirtual-environments","Virtual Environments & pip","J9rM7tWYUq73AiW9CqGkW0bpSbKn9qvu5gGCVDpRVAw",{"id":5650,"title":5651,"body":5652,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":5656,"navigation":66,"order":5657,"path":5658,"questions":5659,"related":207,"seo":5680,"seoDescription":5681,"stem":5682,"subtopic":5683,"topic":819,"topicSlug":5684,"updated":214,"__hash__":5685},"qa\u002Fpython\u002Foop\u002Fabc-protocols.md","Abc Protocols",{"type":58,"value":5653,"toc":5654},[],{"title":61,"searchDepth":22,"depth":22,"links":5655},[],{},6,"\u002Fpython\u002Foop\u002Fabc-protocols",[5660,5664,5668,5672,5676],{"id":5661,"difficulty":63,"q":5662,"a":5663},"what-is-abc","What is an abstract base class and what does @abstractmethod do?","An **abstract base class (ABC)** is a class that **can't be instantiated\ndirectly** and defines a set of methods subclasses **must implement**. You build\none by subclassing `abc.ABC` and decorating required methods with\n**`@abstractmethod`**. Python refuses to instantiate any subclass that leaves an\nabstract method unimplemented.\n\n```python\nfrom abc import ABC, abstractmethod\n\nclass Shape(ABC):\n    @abstractmethod\n    def area(self):            # subclasses MUST implement this\n        ...\n\nShape()                        # TypeError — can't instantiate abstract class\n\nclass Circle(Shape):\n    def __init__(self, r):\n        self.r = r\n    def area(self):            # concrete implementation\n        return 3.14159 * self.r ** 2\n\nCircle(2).area()               # 12.566... — works\n```\n\n`@abstractmethod` turns the \"must implement\" contract into an **enforced,\nload-time check** rather than a runtime `NotImplementedError` later. It defines\nan interface that subclasses are required to fulfill.\n",{"id":5665,"difficulty":63,"q":5666,"a":5667},"why-use-abcs","Why use ABCs instead of just regular classes?","ABCs **enforce an interface** — they guarantee at instantiation time that\nsubclasses provide the required methods, catching mistakes **early** instead of\nblowing up deep in your code. They also document intent clearly and integrate\nwith `isinstance` checks, so callers can verify capabilities.\n\n```python\nfrom abc import ABC, abstractmethod\n\nclass Storage(ABC):\n    @abstractmethod\n    def save(self, key, value): ...\n    @abstractmethod\n    def load(self, key): ...\n\nclass FileStorage(Storage):\n    def save(self, key, value): ...\n    # forgot load() ...\n\nFileStorage()      # TypeError — flags the missing method immediately\nisinstance(FileStorage, type) and issubclass(FileStorage, Storage)  # True\n```\n\nUse an ABC when you have a **family of classes that must share a contract** and\nyou want that contract enforced. For looser, optional interfaces, plain duck\ntyping or a `Protocol` may fit better.\n",{"id":5669,"difficulty":84,"q":5670,"a":5671},"collections-abc","What is collections.abc and how is it useful?","`collections.abc` provides the **standard ABCs for Python's container\nprotocols** — `Iterable`, `Iterator`, `Sequence`, `Mapping`, `Hashable`, and\nmore. You use them two ways: as a **base class** to inherit mixin methods, and\nin **`isinstance` checks** to test whether an object supports a protocol.\n\n```python\nfrom collections.abc import Iterable, Sequence, Mapping\n\nisinstance([1, 2], Iterable)   # True\nisinstance(\"abc\", Sequence)    # True\nisinstance({}, Mapping)        # True\n\nclass MyList(Sequence):        # inherit the protocol's mixin methods\n    def __init__(self, data):\n        self._data = data\n    def __getitem__(self, i):\n        return self._data[i]\n    def __len__(self):\n        return len(self._data)\n    # get __contains__, __iter__, __reversed__, index, count for FREE\n```\n\nSubclassing `Sequence` and implementing just `__getitem__` + `__len__` gives you\na fully functional sequence. Prefer these standard ABCs over inventing your own\nfor container-like types.\n",{"id":5673,"difficulty":63,"q":5674,"a":5675},"duck-typing-vs-abcs","What is the difference between duck typing and ABCs?","**Duck typing** is \"if it walks like a duck and quacks like a duck, it's a\nduck\" — Python doesn't check the type, it just **tries the operation** and works\nif the needed methods exist. **ABCs add an explicit, enforced contract** on top,\nletting you assert membership and catch missing methods up front.\n\n```python\n# Duck typing — no declared interface, just call and hope:\ndef make_it_quack(thing):\n    thing.quack()          # works for ANYTHING with a quack() method\n\nclass Dog:\n    def quack(self): return \"woof-quack\"\nmake_it_quack(Dog())       # works — Dog \"is\" a duck here\n\n# ABC — explicit, checkable contract:\nfrom abc import ABC, abstractmethod\nclass Duck(ABC):\n    @abstractmethod\n    def quack(self): ...\n```\n\nDuck typing is flexible and Pythonic but defers errors to runtime; ABCs trade\nsome flexibility for **early enforcement and clear interfaces**. Use duck typing\nfor loose coupling, ABCs when you want guarantees.\n",{"id":5677,"difficulty":84,"q":5678,"a":5679},"typing-protocol","What is typing.Protocol and how does it relate to duck typing?","`typing.Protocol` enables **structural typing** (\"static duck typing\"): a class\nsatisfies a protocol simply by **having the right methods\u002Fattributes** — no\nexplicit inheritance needed. Type checkers verify the structure **statically**,\ngiving you duck typing's flexibility **with** static safety. Add\n**`@runtime_checkable`** to also allow `isinstance` checks at runtime.\n\n```python\nfrom typing import Protocol, runtime_checkable\n\n@runtime_checkable\nclass Drawable(Protocol):\n    def draw(self) -> str: ...     # required shape, not inheritance\n\nclass Button:                      # does NOT inherit Drawable\n    def draw(self) -> str:\n        return \"[Button]\"\n\ndef render(item: Drawable) -> str: # type checker accepts Button\n    return item.draw()\n\nrender(Button())                   # works — structural match\nisinstance(Button(), Drawable)     # True — thanks to @runtime_checkable\n```\n\nUnlike ABCs, classes don't register or subclass anything — matching the\n**structure is enough**. Note `@runtime_checkable` only checks method\n**names\u002Fexistence**, not signatures. Use Protocols for flexible, statically\nverified interfaces; use ABCs when you need shared implementation or explicit\nregistration.\n",{"description":61},"Python interview questions on abstract base classes and @abstractmethod, why use ABCs, collections.abc, duck typing vs ABCs, and typing.Protocol for structural\u002Fstatic duck typing with runtime_checkable.","python\u002Foop\u002Fabc-protocols","Abstract Base Classes & Protocols","oop","ND9wrQMm980ybmmy5dud6WKKaNzHF-LWIzfyLRcQJ5Q",{"id":5687,"title":5688,"body":5689,"description":61,"difficulty":71,"extension":64,"framework":30,"frameworkSlug":28,"meta":5693,"navigation":66,"order":22,"path":5694,"questions":5695,"related":207,"seo":5720,"seoDescription":5721,"stem":5722,"subtopic":5723,"topic":819,"topicSlug":5684,"updated":214,"__hash__":5724},"qa\u002Fpython\u002Foop\u002Fclasses.md","Classes",{"type":58,"value":5690,"toc":5691},[],{"title":61,"searchDepth":22,"depth":22,"links":5692},[],{},"\u002Fpython\u002Foop\u002Fclasses",[5696,5700,5704,5708,5712,5716],{"id":5697,"difficulty":71,"q":5698,"a":5699},"class-vs-instance","What is the difference between a class and an instance?","A **class** is a **blueprint** — it defines the attributes and methods that\nobjects of that type will have. An **instance** is a concrete **object built\nfrom that blueprint**, with its own state. You write the class once and create\nmany instances from it.\n\n```python\nclass Dog:                 # the blueprint\n    def __init__(self, name):\n        self.name = name   # per-instance state\n\nrex = Dog(\"Rex\")           # an instance\nfido = Dog(\"Fido\")         # a separate instance\nrex.name                   # 'Rex'\nfido.name                  # 'Fido' — independent state\ntype(rex)                  # \u003Cclass '__main__.Dog'>\n```\n\nThe class itself is also an object (of type `type`). Each instance carries its\nown data but shares the class's methods. Think of the class as the cookie\ncutter and the instances as the cookies.\n",{"id":5701,"difficulty":63,"q":5702,"a":5703},"init-vs-new","What is the difference between __init__ and __new__?","`__new__` **creates and returns the new object**; `__init__` **initializes**\nthat already-created object. `__new__` runs first and is a static method that\nreceives the **class**; `__init__` runs second and receives the **instance**\n(`self`) it should configure. `__init__` must return `None`.\n\n```python\nclass Widget:\n    def __new__(cls, *args):\n        print(\"__new__ — allocating\")\n        return super().__new__(cls)   # returns the instance\n    def __init__(self, size):\n        print(\"__init__ — configuring\")\n        self.size = size              # sets state on self\n\nw = Widget(10)   # prints __new__ then __init__\n```\n\nYou rarely override `__new__` — it's mainly for **immutable types** (subclassing\n`int`\u002F`str`\u002F`tuple`), singletons, or metaclass tricks. For everyday classes,\njust use `__init__`.\n",{"id":5705,"difficulty":71,"q":5706,"a":5707},"what-is-self","What is `self` in Python?","`self` is the **instance the method was called on** — it's how a method accesses\nthat object's attributes and other methods. It isn't a keyword; it's just the\nconventional **name of the first parameter**. Python passes the instance\nautomatically when you call `obj.method()`.\n\n```python\nclass Counter:\n    def __init__(self):\n        self.count = 0\n    def increment(self):\n        self.count += 1        # self refers to this instance\n\nc = Counter()\nc.increment()                  # Python passes c as self\nCounter.increment(c)           # exactly equivalent — self is explicit here\n```\n\nSo `c.increment()` is sugar for `Counter.increment(c)`. The explicitness is\ndeliberate — Python makes the instance visible rather than hiding it like\n`this` in other languages.\n",{"id":5709,"difficulty":63,"q":5710,"a":5711},"instance-vs-class-attributes","What is the difference between instance and class attributes?","A **class attribute** is defined in the class body and **shared by every\ninstance**; an **instance attribute** is set on `self` (usually in `__init__`)\nand is **unique per object**. Attribute lookup checks the instance first, then\nfalls back to the class.\n\n```python\nclass Dog:\n    species = \"Canis familiaris\"   # class attribute — shared\n    def __init__(self, name):\n        self.name = name           # instance attribute — per-object\n\na, b = Dog(\"Rex\"), Dog(\"Fido\")\na.species                # 'Canis familiaris' (from the class)\na.name, b.name           # 'Rex', 'Fido' (independent)\na.species = \"wolf\"       # creates an instance attr that SHADOWS the class one\nb.species                # still 'Canis familiaris'\n```\n\nWatch the classic trap: a **mutable** class attribute (like `[]`) is shared and\nwill leak state between instances — initialize mutable state in `__init__`.\n",{"id":5713,"difficulty":63,"q":5714,"a":5715},"repr-vs-str","What is the difference between __repr__ and __str__?","`__repr__` is the **unambiguous, developer-facing** representation — ideally\nsomething that could recreate the object — and is what you see in the REPL and\nin containers. `__str__` is the **readable, user-facing** string used by\n`print()` and `str()`. If `__str__` is missing, Python **falls back to\n`__repr__`**.\n\n```python\nclass Point:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __repr__(self):\n        return f\"Point(x={self.x}, y={self.y})\"   # for developers\n    def __str__(self):\n        return f\"({self.x}, {self.y})\"            # for users\n\np = Point(1, 2)\nprint(p)     # (1, 2)        — __str__\nrepr(p)      # 'Point(x=1, y=2)'  — __repr__\n[p]          # [Point(x=1, y=2)]  — containers use __repr__\n```\n\nRule of thumb: always define `__repr__`; add `__str__` only when you need a\ndistinct friendly form.\n",{"id":5717,"difficulty":63,"q":5718,"a":5719},"object-creation-flow","What happens, step by step, when you call ClassName()?","Calling `ClassName(args)` invokes the class's metaclass `__call__`, which\norchestrates two steps: it calls **`__new__(cls, args)`** to allocate the\nobject, then — if `__new__` returned an instance of `cls` — calls\n**`__init__(instance, args)`** to initialize it, and finally returns the\ninstance.\n\n```python\nclass Demo:\n    def __new__(cls, *a):\n        print(\"1. __new__\")\n        return super().__new__(cls)\n    def __init__(self, *a):\n        print(\"2. __init__\")\n\nd = Demo()       # prints: 1. __new__  then  2. __init__\n# 3. d is now bound to the fully initialized instance\n```\n\nKey subtlety: if `__new__` returns an object that is **not** an instance of the\nclass, `__init__` is **skipped entirely**. For normal classes you never see\nthis machinery — you just call the class and get back a ready object.\n",{"description":61},"Python interview questions on classes vs instances, __init__ vs __new__, the self parameter, instance vs class attributes, __repr__ vs __str__, and the object creation flow.","python\u002Foop\u002Fclasses","Classes, Instances & __init__","ouDK0ESDWwDR7Ofpyzn1mO8dgBG_yOsNKMgJuy_V_Uo",{"id":5726,"title":5727,"body":5728,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5732,"navigation":66,"order":50,"path":5733,"questions":5734,"related":207,"seo":5758,"seoDescription":5759,"stem":5760,"subtopic":5761,"topic":819,"topicSlug":5684,"updated":214,"__hash__":5762},"qa\u002Fpython\u002Foop\u002Fdataclasses-slots.md","Dataclasses Slots",{"type":58,"value":5729,"toc":5730},[],{"title":61,"searchDepth":22,"depth":22,"links":5731},[],{},"\u002Fpython\u002Foop\u002Fdataclasses-slots",[5735,5739,5742,5746,5750,5754],{"id":5736,"difficulty":71,"q":5737,"a":5738},"what-dataclass-generates","What does the @dataclass decorator generate for you?","`@dataclass` auto-generates the **boilerplate dunder methods** from the\nclass's annotated fields — primarily **`__init__`**, **`__repr__`**, and\n**`__eq__`**. You declare fields with type hints (and optional defaults) and\nskip writing the constructor by hand.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass Point:\n    x: int\n    y: int = 0           # field with a default\n\np = Point(1, 2)\np                        # Point(x=1, y=2)        — generated __repr__\np == Point(1, 2)         # True                   — generated __eq__\n# __init__(self, x, y=0) was generated automatically\n```\n\nYou can opt into more (`order=True` for comparison operators, `frozen=True` for\nimmutability). It removes the repetitive plumbing while leaving normal methods\nup to you.\n",{"id":4936,"difficulty":63,"q":5740,"a":5741},"What does frozen=True do on a dataclass?","`@dataclass(frozen=True)` makes instances **immutable** — assigning to a field\nafter creation raises **`FrozenInstanceError`**. As a bonus, frozen dataclasses\nget a generated **`__hash__`**, so they're usable as **dict keys and set\nmembers**.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Point:\n    x: int\n    y: int\n\np = Point(1, 2)\np.x = 9            # FrozenInstanceError — immutable\n{p: \"origin\"}      # hashable — works as a dict key\n{Point(1, 2), Point(1, 2)}   # one element — equal and hashable\n```\n\nFrozen dataclasses are the concise, modern way to define **immutable value\nobjects**. Use them whenever an object represents a value that shouldn't change\nafter creation.\n",{"id":5743,"difficulty":84,"q":5744,"a":5745},"default-factory","Why must mutable dataclass defaults use field(default_factory=...)?","A bare mutable default (`tags: list = []`) would be **shared across all\ninstances** — the same default-argument trap as in regular functions — so\ndataclasses **forbid it and raise `ValueError`**. Instead, pass\n**`field(default_factory=list)`**, a zero-arg callable that creates a **fresh\nobject per instance**.\n\n```python\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Article:\n    title: str\n    tags: list = field(default_factory=list)   # new list each instance\n    # tags: list = []   # would raise ValueError at class-definition time\n\na, b = Article(\"A\"), Article(\"B\")\na.tags.append(\"python\")\nb.tags             # []  — independent, no shared state\n```\n\nUse `default_factory` for any mutable default (`list`, `dict`, `set`) or for a\nvalue that must be computed at construction time. Plain immutable defaults\n(numbers, strings, tuples) are fine inline.\n",{"id":5747,"difficulty":84,"q":5748,"a":5749},"slots","What is __slots__ and what does it buy you?","`__slots__` declares a **fixed set of allowed attributes**, so instances store\nthem in a compact array instead of a per-instance **`__dict__`**. This **saves\nsignificant memory** (no dict per object) and gives **faster attribute access**.\nThe trade-off: you **can't add new attributes** not listed in slots.\n\n```python\nclass Point:\n    __slots__ = (\"x\", \"y\")     # no per-instance __dict__\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n\np = Point(1, 2)\np.x               # 2 — fast access\np.z = 3           # AttributeError — 'z' not in __slots__\n# p.__dict__      # also AttributeError — there is no dict\n\nfrom dataclasses import dataclass\n@dataclass(slots=True)        # dataclasses can generate slots (3.10+)\nclass Fast:\n    x: int\n    y: int\n```\n\nReach for `__slots__` when you create **huge numbers of small objects** and\nmemory matters. For ordinary classes the flexibility of `__dict__` is usually\nworth more than the savings.\n",{"id":5751,"difficulty":63,"q":5752,"a":5753},"dataclass-vs-namedtuple","When would you choose a dataclass over a namedtuple or NamedTuple?","A **`namedtuple`**\u002F**`typing.NamedTuple`** is an **immutable tuple** subclass —\nlightweight, hashable, iterable, and index-accessible, but values can't change.\nA **`@dataclass`** is a regular class — **mutable by default**, supports methods,\ninheritance, and `default_factory`, but isn't a tuple (no unpacking\u002Findexing\nunless you add it).\n\n```python\nfrom typing import NamedTuple\nfrom dataclasses import dataclass\n\nclass PointNT(NamedTuple):     # immutable, tuple-like\n    x: int\n    y: int\nx, y = PointNT(1, 2)           # unpacks like a tuple\n\n@dataclass\nclass PointDC:                 # mutable, full class\n    x: int\n    y: int\n    def shift(self, dx):       # can hold real methods\n        self.x += dx\n\nPointNT(1, 2)[0]   # 1 — index access (tuple)\nPointDC(1, 2).shift(5)         # mutate in place\n```\n\nChoose a **NamedTuple** for small immutable records and tuple semantics; choose a\n**dataclass** when you need mutability, methods, or richer field control. Use\n`frozen=True` dataclasses for immutable value objects that still want class\nfeatures.\n",{"id":5755,"difficulty":63,"q":5756,"a":5757},"post-init","What is __post_init__ used for?","`__post_init__` runs **automatically right after the generated `__init__`** —\nit's the hook for **validation and derived fields** that depend on the\nconstructor arguments. It pairs with `field(init=False)` to declare attributes\nthat aren't constructor parameters but are computed afterward.\n\n```python\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Rectangle:\n    width: float\n    height: float\n    area: float = field(init=False)     # not a constructor arg\n\n# filled in after __init__:\n    def __post_init__(self):\n        if self.width \u003C= 0 or self.height \u003C= 0:\n            raise ValueError(\"dimensions must be positive\")   # validation\n        self.area = self.width * self.height                  # derived field\n\nr = Rectangle(3, 4)\nr.area            # 12 — computed in __post_init__\nRectangle(-1, 4)  # ValueError\n```\n\nUse `__post_init__` whenever a dataclass needs logic the auto-generated\n`__init__` can't express — validation, normalization, or fields derived from\nothers.\n",{"description":61},"Python interview questions on @dataclass — generated methods, frozen=True, field(default_factory=...) for mutable defaults, __slots__ for memory and speed, dataclass vs namedtuple vs NamedTuple, and __post_init__.","python\u002Foop\u002Fdataclasses-slots","Dataclasses & __slots__","rbgsaK-ivBYw25DXEMFBiwSKrF17EhRciQ-ctqZKl34",{"id":5764,"title":5765,"body":5766,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":5770,"navigation":66,"order":31,"path":5771,"questions":5772,"related":207,"seo":5801,"seoDescription":5802,"stem":5803,"subtopic":5804,"topic":819,"topicSlug":5684,"updated":214,"__hash__":5805},"qa\u002Fpython\u002Foop\u002Fdunder-methods.md","Dunder Methods",{"type":58,"value":5767,"toc":5768},[],{"title":61,"searchDepth":22,"depth":22,"links":5769},[],{},"\u002Fpython\u002Foop\u002Fdunder-methods",[5773,5777,5781,5785,5789,5793,5797],{"id":5774,"difficulty":63,"q":5775,"a":5776},"what-are-dunder-methods","What are dunder (magic) methods?","**Dunder methods** (\"double underscore\", e.g. `__init__`, `__len__`) are special\nhooks Python calls **implicitly** to make your objects work with built-in syntax\nand functions. They are how Python implements **operator overloading and\nprotocols** — `len(x)` calls `x.__len__()`, `x + y` calls `x.__add__(y)`,\n`x[0]` calls `x.__getitem__(0)`.\n\n```python\nclass Box:\n    def __init__(self, items):\n        self.items = items\n    def __len__(self):\n        return len(self.items)   # makes len(box) work\n\nb = Box([1, 2, 3])\nlen(b)        # 3 — Python calls b.__len__()\n```\n\nThey're sometimes called \"magic methods\" but there's no magic — they're a\ndocumented protocol. Implementing the right dunders makes your objects feel like\nnative Python types.\n",{"id":5778,"difficulty":63,"q":5779,"a":5780},"repr-str-dunder","How do __repr__ and __str__ control how an object prints?","`__repr__` defines the **unambiguous developer representation** (REPL output,\ncontainers, `repr()`); `__str__` defines the **human-readable** form (`print()`,\n`str()`). When `__str__` is absent, Python **falls back to `__repr__`** — so\n`__repr__` is the one to always implement.\n\n```python\nclass Temperature:\n    def __init__(self, c):\n        self.c = c\n    def __repr__(self):\n        return f\"Temperature({self.c})\"     # eval-friendly\n    def __str__(self):\n        return f\"{self.c}°C\"                 # friendly\n\nt = Temperature(20)\nstr(t)    # '20°C'\nrepr(t)   # 'Temperature(20)'\n```\n\nA good `__repr__` ideally lets `eval(repr(obj))` reconstruct the object. Always\ndefine `__repr__`; add `__str__` only when a separate user-facing string helps.\n",{"id":5782,"difficulty":84,"q":5783,"a":5784},"eq-and-hash","How do __eq__ and __hash__ work together?","`__eq__` defines **value equality** (`==`); `__hash__` returns the integer used\nby **dicts and sets**. They have a **contract**: if `a == b` then\n`hash(a) == hash(b)`. Defining `__eq__` **alone** sets `__hash__ = None`, making\ninstances **unhashable** — so define both, derived from the **same immutable\nfields**.\n\n```python\nclass Point:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __eq__(self, other):\n        return (self.x, self.y) == (other.x, other.y)\n    def __hash__(self):\n        return hash((self.x, self.y))    # same fields as __eq__\n\n{Point(1, 2), Point(1, 2)}   # one element — treated as equal\n```\n\nOnly hash on fields that never change after creation. If you break the contract,\nobjects you store in a set\u002Fdict become unfindable.\n",{"id":5786,"difficulty":84,"q":5787,"a":5788},"operator-overloading","How do you overload operators like + and *?","Implement the matching **arithmetic dunder**: `__add__` for `+`, `__sub__` for\n`-`, `__mul__` for `*`, `__lt__` for `\u003C`, and so on. Python calls them when the\noperator is used. Return a **new object** (or `NotImplemented` if you can't\nhandle the other operand, so Python can try the reflected method like\n`__radd__`).\n\n```python\nclass Vector:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __add__(self, other):\n        return Vector(self.x + other.x, self.y + other.y)   # v1 + v2\n    def __mul__(self, k):\n        return Vector(self.x * k, self.y * k)               # v * 3\n    def __repr__(self):\n        return f\"Vector({self.x}, {self.y})\"\n\nVector(1, 2) + Vector(3, 4)   # Vector(4, 6)\nVector(1, 2) * 3              # Vector(3, 6)\n```\n\nReturn `NotImplemented` (not raise) for unsupported types so Python can fall\nback gracefully. Don't overload operators in surprising ways — keep semantics\nintuitive.\n",{"id":5790,"difficulty":84,"q":5791,"a":5792},"sequence-protocol","How do __len__ and __getitem__ make an object behave like a sequence?","Implementing `__len__` makes `len(obj)` work, and `__getitem__` makes\n**indexing, slicing, and iteration** work — Python can iterate by calling\n`__getitem__(0)`, `__getitem__(1)`, ... until `IndexError`, even without an\n`__iter__`. Together they form the **sequence protocol**.\n\n```python\nclass Playlist:\n    def __init__(self, songs):\n        self.songs = songs\n    def __len__(self):\n        return len(self.songs)         # len(pl)\n    def __getitem__(self, i):\n        return self.songs[i]           # pl[0], pl[1:3], and iteration\n\npl = Playlist([\"a\", \"b\", \"c\"])\nlen(pl)          # 3\npl[1]            # 'b'\nfor s in pl:     # iterates via __getitem__\n    print(s)\n```\n\nAdd `__contains__` for `in` and `__setitem__` for assignment. This duck-typed\nprotocol is why custom containers feel like lists.\n",{"id":5794,"difficulty":63,"q":5795,"a":5796},"call-dunder","What does __call__ do?","`__call__` makes an **instance itself callable** like a function — `obj()`\ninvokes `obj.__call__()`. This lets objects **carry state between calls**, which\na plain function can't do as cleanly. It's the basis of function objects and\nmany decorators.\n\n```python\nclass Multiplier:\n    def __init__(self, factor):\n        self.factor = factor       # remembered state\n    def __call__(self, x):\n        return x * self.factor     # obj(x)\n\ndouble = Multiplier(2)\ndouble(5)         # 10 — calling the instance\ncallable(double)  # True\n```\n\nUse it for **stateful callables** — configurable functions, accumulators, or\nclass-based decorators. If you just need behavior without state, a closure or\nplain function is simpler.\n",{"id":5798,"difficulty":63,"q":5799,"a":5800},"total-ordering","What does functools.total_ordering do?","`@functools.total_ordering` is a class decorator that **fills in the missing\ncomparison operators** from the ones you define. You provide `__eq__` plus **one**\nof `__lt__`, `__le__`, `__gt__`, `__ge__`, and it generates the rest — saving you\nfrom writing all six.\n\n```python\nfrom functools import total_ordering\n\n@total_ordering\nclass Version:\n    def __init__(self, n):\n        self.n = n\n    def __eq__(self, other):\n        return self.n == other.n\n    def __lt__(self, other):\n        return self.n \u003C other.n     # only this + __eq__ needed\n\nVersion(1) \u003C Version(2)    # True\nVersion(2) >= Version(1)   # True — generated by total_ordering\nsorted([Version(3), Version(1), Version(2)])  # works\n```\n\nThe trade-off is a small performance cost from derived comparisons; for\nhot-path code, define all operators explicitly. Otherwise it's a clean way to\nget full ordering with minimal boilerplate.\n",{"description":61},"Python interview questions on dunder\u002Fmagic methods — __repr__\u002F__str__, __eq__ and __hash__, operator overloading with __add__, the sequence protocol (__len__\u002F__getitem__), __call__, and functools.total_ordering.","python\u002Foop\u002Fdunder-methods","Dunder \u002F Magic Methods","ncqznv9sUn2_SLebvm5cJygSM3_p-P2icZsoSaPIlxo",{"id":5807,"title":5808,"body":5809,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":5813,"navigation":66,"order":12,"path":5814,"questions":5815,"related":207,"seo":5835,"seoDescription":5836,"stem":5837,"subtopic":5838,"topic":819,"topicSlug":5684,"updated":214,"__hash__":5839},"qa\u002Fpython\u002Foop\u002Finheritance.md","Inheritance",{"type":58,"value":5810,"toc":5811},[],{"title":61,"searchDepth":22,"depth":22,"links":5812},[],{},"\u002Fpython\u002Foop\u002Finheritance",[5816,5820,5824,5828,5831],{"id":5817,"difficulty":71,"q":5818,"a":5819},"single-vs-multiple","What is the difference between single and multiple inheritance?","**Single inheritance** means a class derives from exactly one parent; **multiple\ninheritance** means it lists more than one base class. Python supports both —\nmultiple inheritance is what lets you compose behaviour from several sources at\nonce.\n\n```python\nclass Animal:\n    def eat(self): print(\"eating\")\n\nclass Dog(Animal):          # single inheritance\n    def bark(self): print(\"woof\")\n\nclass Swimmer: ...\nclass Flyer: ...\nclass Duck(Animal, Swimmer, Flyer):  # multiple inheritance\n    pass\n```\n\nMultiple inheritance is powerful but can create ambiguity about *which* parent's\nmethod wins — that ambiguity is resolved by the **MRO**. Rule of thumb: prefer\nsingle inheritance plus small **mixins** over deep, wide hierarchies.\n",{"id":5821,"difficulty":84,"q":5822,"a":5823},"what-is-mro","What is the MRO and how is it computed?","The **MRO (Method Resolution Order)** is the linear, ordered list of classes\nPython searches when looking up an attribute or method on an instance. CPython\nbuilds it with the **C3 linearization** algorithm, which guarantees a consistent\norder that respects each class's own order of bases and never places a parent\nbefore its child.\n\n```python\nclass A: ...\nclass B(A): ...\nclass C(A): ...\nclass D(B, C): ...\n\nD.__mro__            # (D, B, C, A, object)\nD.mro()             # same, as a list\n```\n\nC3 produces a single deterministic order (or raises `TypeError` if no consistent\norder exists). Attribute lookup walks this list left to right and stops at the\nfirst match. Rule of thumb: read `Cls.__mro__` whenever multiple inheritance\nsurprises you — it tells you exactly who wins.\n",{"id":5825,"difficulty":84,"q":5826,"a":5827},"how-super-works","How does super() actually work?","`super()` does **not** simply call \"the parent class\" — it calls the **next class\nin the instance's MRO**, starting after the current class. That cooperative\nbehaviour is what makes multiple inheritance work correctly: each class delegates\nto whatever comes next, regardless of the static hierarchy.\n\n```python\nclass A:\n    def greet(self): print(\"A\")\nclass B(A):\n    def greet(self): print(\"B\"); super().greet()\nclass C(A):\n    def greet(self): print(\"C\"); super().greet()\nclass D(B, C):\n    def greet(self): print(\"D\"); super().greet()\n\nD().greet()   # D, B, C, A  — follows D.__mro__, not B's parent\n```\n\nNote `super().greet()` inside `B` calls `C`, not `A`, because the MRO of a `D`\ninstance puts `C` after `B`. Rule of thumb: in a cooperative hierarchy every\noverride should call `super()` so the whole chain runs exactly once.\n",{"id":3955,"difficulty":84,"q":5829,"a":5830},"What is the diamond problem and how does Python solve it?","The **diamond problem** arises when two classes (`B`, `C`) inherit from a common\nbase (`A`), and a fourth class (`D`) inherits from both. The question is: when\n`D` calls an inherited method, is `A`'s code run **once or twice**? Naive\nlanguages run it twice; Python's **C3 MRO** guarantees `A` appears **exactly\nonce**, so cooperative `super()` calls run it a single time.\n\n```python\nclass A:\n    def __init__(self): print(\"A\"); \nclass B(A):\n    def __init__(self): print(\"B\"); super().__init__()\nclass C(A):\n    def __init__(self): print(\"C\"); super().__init__()\nclass D(B, C):\n    def __init__(self): print(\"D\"); super().__init__()\n\nD()   # D, B, C, A  — A's __init__ runs ONCE\n```\n\nThe MRO `(D, B, C, A, object)` linearizes the diamond into a clean chain. Rule of\nthumb: the diamond is only safe when every class in it uses `super()` consistently\n— mixing `super()` with hard-coded `Base.__init__(self)` calls breaks the\nguarantee.\n",{"id":5832,"difficulty":63,"q":5833,"a":5834},"mixins-and-abc","What are mixins and abstract base classes?","A **mixin** is a small class that provides a focused slice of behaviour meant to be\ncombined into other classes via multiple inheritance — it isn't useful on its own\nand usually has no `__init__`. An **abstract base class (ABC)**, from the `abc`\nmodule, defines an interface with `@abstractmethod`s and **cannot be instantiated**\nuntil every abstract method is overridden.\n\n```python\nfrom abc import ABC, abstractmethod\n\nclass JsonMixin:                 # mixin: adds one capability\n    def to_json(self): import json; return json.dumps(self.__dict__)\n\nclass Shape(ABC):                # abstract base: defines a contract\n    @abstractmethod\n    def area(self): ...\n\nclass Circle(Shape, JsonMixin):\n    def __init__(self, r): self.r = r\n    def area(self): return 3.14159 * self.r ** 2\n\nShape()    # TypeError: can't instantiate abstract class\n```\n\nUse mixins to share reusable behaviour and ABCs to enforce that subclasses\nimplement a required interface (`isinstance` checks also work against ABCs). Rule\nof thumb: mixins say \"you *can* do this\", ABCs say \"you *must* do this\".\n",{"description":61},"Python interview questions on single vs multiple inheritance, the MRO and C3 linearization, super(), the diamond problem, mixins, and abstract base classes.","python\u002Foop\u002Finheritance","Inheritance & the MRO","lr7N1CknUWOM5mCsCVypmlwzPFk9qinVKOEqgWAED8Y",{"id":5841,"title":5842,"body":5843,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5847,"navigation":66,"order":40,"path":5848,"questions":5849,"related":207,"seo":5870,"seoDescription":5871,"stem":5872,"subtopic":5873,"topic":819,"topicSlug":5684,"updated":214,"__hash__":5874},"qa\u002Fpython\u002Foop\u002Fmethods-properties.md","Methods Properties",{"type":58,"value":5844,"toc":5845},[],{"title":61,"searchDepth":22,"depth":22,"links":5846},[],{},"\u002Fpython\u002Foop\u002Fmethods-properties",[5850,5854,5858,5862,5866],{"id":5851,"difficulty":63,"q":5852,"a":5853},"instance-class-static-methods","What is the difference between an instance method, @classmethod, and @staticmethod?","An **instance method** takes `self` and operates on a specific object. A\n**`@classmethod`** takes `cls` (the class, not an instance) and works on\n**class-level state** or builds instances. A **`@staticmethod`** takes\n**neither** — it's a plain function namespaced inside the class, with no access\nto instance or class state.\n\n```python\nclass Pizza:\n    base_price = 10\n    def __init__(self, toppings):\n        self.toppings = toppings\n    def total(self):                    # instance method — uses self\n        return self.base_price + len(self.toppings)\n    @classmethod\n    def margherita(cls):                # classmethod — uses cls\n        return cls([\"mozzarella\", \"basil\"])\n    @staticmethod\n    def is_valid_topping(name):         # staticmethod — no self\u002Fcls\n        return name.isalpha()\n\nPizza.is_valid_topping(\"ham\")   # True — no instance needed\nPizza.margherita().total()      # 12\n```\n\nUse an instance method for per-object behavior, a classmethod for\nclass-aware logic (e.g. alternative constructors), and a staticmethod for a\nrelated helper that happens to live on the class.\n",{"id":5855,"difficulty":63,"q":5856,"a":5857},"classmethod-constructor","How do you use a classmethod as an alternative constructor?","A classmethod receives `cls`, so it can **build and return a new instance** from\na different input format — giving you multiple named constructors beyond\n`__init__`. Using `cls` (not the hard-coded class name) means **subclasses get\nthe right type** automatically.\n\n```python\nclass Date:\n    def __init__(self, year, month, day):\n        self.year, self.month, self.day = year, month, day\n    @classmethod\n    def from_string(cls, text):\n        y, m, d = map(int, text.split(\"-\"))\n        return cls(y, m, d)             # returns the (sub)class instance\n    @classmethod\n    def today(cls):\n        import datetime\n        t = datetime.date.today()\n        return cls(t.year, t.month, t.day)\n\nDate.from_string(\"2026-06-18\")   # alternative constructor\nDate.today()\n```\n\nThis is the idiomatic Python pattern (`dict.fromkeys`, `datetime.fromtimestamp`)\nfor \"make one of these, but from X\" — clearer than overloading `__init__` with\nflags.\n",{"id":5859,"difficulty":63,"q":5860,"a":5861},"property-getter-setter","How does @property work with a getter and setter?","`@property` turns a method into a **managed attribute** — you access it like\n`obj.x` (no parentheses), but a method runs behind the scenes. The matching\n`@x.setter` runs on assignment, letting you add **validation** without changing\nthe public interface.\n\n```python\nclass Account:\n    def __init__(self, balance):\n        self._balance = balance         # \"private\" backing field\n    @property\n    def balance(self):                  # getter — runs on read\n        return self._balance\n    @balance.setter\n    def balance(self, value):           # setter — runs on write\n        if value \u003C 0:\n            raise ValueError(\"balance cannot be negative\")\n        self._balance = value\n\nacc = Account(100)\nacc.balance          # 100 — looks like an attribute, calls the getter\nacc.balance = 50     # calls the setter (validated)\nacc.balance = -1     # ValueError\n```\n\nThe convention is a `_name` backing attribute behind a public property. Omit the\nsetter to make the property read-only.\n",{"id":5863,"difficulty":63,"q":5864,"a":5865},"why-properties-over-getters","Why do properties beat Java-style getter\u002Fsetter methods?","In Python you **start with a plain attribute** and only convert it to a\n`@property` later **if** you need validation or computation — **without changing\nthe call sites**. So you avoid the Java habit of pre-emptively writing\n`getX()`\u002F`setX()` \"just in case\". The public API stays `obj.x`.\n\n```python\n# Start simple — public attribute:\nclass Circle:\n    def __init__(self, radius):\n        self.radius = radius\n\nc = Circle(5)\nc.radius            # direct access — no ceremony\n\n# Later, add validation transparently — callers don't change:\nclass Circle:\n    def __init__(self, radius):\n        self.radius = radius\n    @property\n    def radius(self):\n        return self._radius\n    @radius.setter\n    def radius(self, value):\n        if value \u003C= 0:\n            raise ValueError(\"radius must be positive\")\n        self._radius = value\n```\n\nThis is the \"uniform access principle\": callers can't tell whether `obj.x` is a\nstored value or computed. Don't write getters\u002Fsetters upfront — reach for a\nproperty only when behavior is needed.\n",{"id":5867,"difficulty":71,"q":5868,"a":5869},"computed-readonly-properties","How do you create a computed or read-only property?","A property with **only a getter** (no setter) is **read-only** — assigning to it\nraises `AttributeError`. A **computed property** derives its value from other\nattributes on each access, so it stays in sync automatically rather than being\nstored.\n\n```python\nclass Rectangle:\n    def __init__(self, width, height):\n        self.width = width\n        self.height = height\n    @property\n    def area(self):                 # computed — derived on each read\n        return self.width * self.height\n\nr = Rectangle(3, 4)\nr.area           # 12 — computed\nr.width = 5\nr.area           # 20 — automatically reflects the change\nr.area = 99      # AttributeError — read-only (no setter)\n```\n\nFor an expensive computation you only want to run once, use\n`functools.cached_property` instead, which caches the result on first access.\nUse a plain read-only property for cheap derived values.\n",{"description":61},"Python interview questions on instance vs classmethod vs staticmethod, classmethods as alternative constructors, the @property getter\u002Fsetter, why properties beat Java-style accessors, and computed\u002Fread-only properties.","python\u002Foop\u002Fmethods-properties","Methods & Properties","EZTMeTHDuvwapkor3EW7aAeDQlUzCDXBSwLIpBJ6zww",{"id":5876,"title":5877,"body":5878,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5882,"navigation":66,"order":31,"path":5883,"questions":5884,"related":207,"seo":5905,"seoDescription":5906,"stem":5907,"subtopic":5908,"topic":5909,"topicSlug":5910,"updated":214,"__hash__":5911},"qa\u002Fpython\u002Fstdlib\u002Fdatetime.md","Datetime",{"type":58,"value":5879,"toc":5880},[],{"title":61,"searchDepth":22,"depth":22,"links":5881},[],{},"\u002Fpython\u002Fstdlib\u002Fdatetime",[5885,5889,5893,5897,5901],{"id":5886,"difficulty":71,"q":5887,"a":5888},"datetime-date-time","What is the difference between datetime, date, and time?","The `datetime` module provides three core types. **`date`** holds a calendar date\n(year, month, day) with **no time**. **`time`** holds a time of day (hour, minute,\nsecond, microsecond) with **no date**. **`datetime`** combines **both** into a\nsingle timestamp.\n\n```python\nfrom datetime import date, time, datetime\n\nd = date(2026, 6, 18)               # just the date\nt = time(14, 30, 0)                 # just the time of day\ndt = datetime(2026, 6, 18, 14, 30)  # date + time together\n\ndt.date()                           # -> date(2026, 6, 18)\ndt.time()                           # -> time(14, 30)\ndate.today()                        # current date\n```\n\nUse `date` for things like birthdays or due dates where time is irrelevant, `time`\nfor a recurring clock time, and `datetime` for actual events\u002Ftimestamps. Most\nreal-world work uses `datetime`.\n",{"id":5890,"difficulty":84,"q":5891,"a":5892},"naive-aware-zoneinfo","What is the difference between naive and timezone-aware datetimes?","A **naive** datetime has **no timezone info** (`tzinfo` is `None`) — it's just wall\nclock numbers with no reference point, so it's ambiguous. An **aware** datetime\ncarries a `tzinfo`, pinning it to an actual instant. Use the stdlib **`zoneinfo`**\nmodule (Python 3.9+) to attach real IANA timezones.\n\n```python\nfrom datetime import datetime\nfrom zoneinfo import ZoneInfo\n\nnaive = datetime(2026, 6, 18, 14, 30)          # ambiguous — no tz\naware = datetime(2026, 6, 18, 14, 30,\n                 tzinfo=ZoneInfo(\"America\u002FNew_York\"))\n\nutc = aware.astimezone(ZoneInfo(\"UTC\"))        # convert between zones\n```\n\nYou **can't compare or subtract** a naive and an aware datetime — it raises\n`TypeError`. Best practice: store and compute in **UTC-aware** datetimes, and convert\nto local zones only for display.\n",{"id":5894,"difficulty":63,"q":5895,"a":5896},"strftime-strptime","What is the difference between strftime and strptime?","They are inverses. **`strftime`** (\"string **f**rom time\") **formats** a datetime\n**into** a string using format codes. **`strptime`** (\"string **p**arse time\")\n**parses** a string **into** a datetime using a matching format.\n\n```python\nfrom datetime import datetime\n\ndt = datetime(2026, 6, 18, 14, 30)\ns = dt.strftime(\"%Y-%m-%d %H:%M\")       # datetime -> \"2026-06-18 14:30\"\n\nparsed = datetime.strptime(\"2026-06-18 14:30\",\n                           \"%Y-%m-%d %H:%M\")  # str -> datetime\n```\n\nCommon codes: `%Y` (4-digit year), `%m` (month), `%d` (day), `%H` (24-hour),\n`%M` (minute), `%S` (second). To remember: **f** = format (out), **p** = parse (in).\nFor standard ISO strings, `datetime.fromisoformat()` \u002F `.isoformat()` are simpler.\n",{"id":5898,"difficulty":63,"q":5899,"a":5900},"timedelta-arithmetic","How does timedelta arithmetic work?","A **`timedelta`** represents a **duration** — a difference between two points in time.\nSubtracting two datetimes yields a `timedelta`; adding a `timedelta` to a datetime\nshifts it. A `timedelta` stores days, seconds, and microseconds.\n\n```python\nfrom datetime import datetime, timedelta\n\nstart = datetime(2026, 6, 18, 9, 0)\nend   = datetime(2026, 6, 18, 17, 30)\n\nworked = end - start              # timedelta(seconds=30600)\nworked.total_seconds()            # 30600.0\nworked.seconds \u002F\u002F 3600            # 8 (hours portion)\n\ntomorrow = start + timedelta(days=1)      # shift forward\nweek_ago = start - timedelta(weeks=1)     # shift back\n```\n\nUse `total_seconds()` to get the whole duration as a number (the `.seconds`\nattribute is only the sub-day part). `timedelta` makes date math safe — it correctly\nrolls over months and years.\n",{"id":5902,"difficulty":84,"q":5903,"a":5904},"now-vs-utcnow","What is the pitfall with datetime.now() vs utcnow()?","The big trap: **both `datetime.now()` and the old `datetime.utcnow()` return *naive*\ndatetimes**. `now()` gives local wall time, `utcnow()` gives the UTC wall time — but\n**neither attaches a tzinfo**, so a `utcnow()` value silently *looks* like local\ntime and corrupts later conversions. `utcnow()` is **deprecated** in modern Python.\n\n```python\nfrom datetime import datetime\nfrom zoneinfo import ZoneInfo\n\ndatetime.now()                       # naive, local time — ambiguous\ndatetime.utcnow()                    # naive, but labelled nothing! (deprecated)\n\n# correct: an AWARE UTC timestamp\nnow_utc = datetime.now(ZoneInfo(\"UTC\"))\nlocal = datetime.now(ZoneInfo(\"America\u002FNew_York\"))\n```\n\nRule of thumb: **always pass a timezone to `now()`** to get an aware datetime, and\navoid `utcnow()` entirely. Store timestamps as UTC-aware and convert for display.\n",{"description":61},"Python interview questions on datetime vs date vs time, naive vs timezone-aware datetimes with zoneinfo, strftime\u002Fstrptime, timedelta arithmetic, and the now() vs utcnow() pitfall.","python\u002Fstdlib\u002Fdatetime","datetime","Standard Library Essentials","stdlib","5GeL0A_Cp3gxfR8_dMsYRrPzndiAo9KQrpPZqTy-QDE",{"id":5913,"title":5914,"body":5915,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5919,"navigation":66,"order":22,"path":5920,"questions":5921,"related":207,"seo":5942,"seoDescription":5943,"stem":5944,"subtopic":5945,"topic":5909,"topicSlug":5910,"updated":214,"__hash__":5946},"qa\u002Fpython\u002Fstdlib\u002Ffiles-pathlib.md","Files Pathlib",{"type":58,"value":5916,"toc":5917},[],{"title":61,"searchDepth":22,"depth":22,"links":5918},[],{},"\u002Fpython\u002Fstdlib\u002Ffiles-pathlib",[5922,5926,5930,5934,5938],{"id":5923,"difficulty":71,"q":5924,"a":5925},"with-open","Why open files with the `with` statement?","`with open(...)` uses the file as a **context manager**, which **guarantees the file\nis closed** when the block exits — even if an exception is raised. Without it you\nmust remember to call `.close()` manually, and a crash mid-block leaks the handle.\n\n```python\nwith open(\"data.txt\") as f:      # f.close() is automatic\n    contents = f.read()\n# file is closed here, even on error\n\nf = open(\"data.txt\")             # manual style — fragile\ntry:\n    contents = f.read()\nfinally:\n    f.close()\n```\n\nLeaked handles can exhaust OS file descriptors and leave buffered writes unflushed.\nAlways prefer `with` for any resource that needs cleanup (files, locks, sockets).\n",{"id":5927,"difficulty":63,"q":5928,"a":5929},"lazy-iteration","What is the difference between iterating a file and read()\u002Freadlines()?","A file object is its own **iterator**, yielding **one line at a time** and holding\nonly that line in memory. `read()` loads the **entire file** into a single string,\nand `readlines()` loads **all lines into a list** — both can blow up memory on large\nfiles.\n\n```python\nwith open(\"huge.log\") as f:\n    for line in f:               # lazy — one line in memory at a time\n        process(line)\n\nwith open(\"huge.log\") as f:\n    data = f.read()              # whole file as one string\n    lines = f.readlines()        # whole file as a list of strings\n```\n\nIterating is the idiomatic, memory-safe way to process big files line by line.\nReserve `read()`\u002F`readlines()` for small files where you genuinely need the whole\ncontent at once.\n",{"id":5931,"difficulty":63,"q":5932,"a":5933},"text-binary-mode","What is the difference between text and binary mode, and why specify encoding?","**Text mode** (`\"r\"`, the default) decodes bytes into `str` using an **encoding** and\nnormalizes newlines. **Binary mode** (`\"rb\"`\u002F`\"wb\"`) reads and writes raw `bytes`\nwith no decoding — required for images, archives, or any non-text data. In text\nmode you should pass **`encoding=`** explicitly, because the default is\nplatform-dependent.\n\n```python\nwith open(\"notes.txt\", \"r\", encoding=\"utf-8\") as f:\n    text: str = f.read()         # decoded to str\n\nwith open(\"photo.jpg\", \"rb\") as f:\n    raw: bytes = f.read()        # raw bytes, no decoding\n```\n\nRelying on the default encoding is a classic cross-platform bug (UTF-8 on Linux\u002FMac,\noften a legacy codepage on Windows). Always specify `encoding=\"utf-8\"` for text, and\nuse binary mode for everything that isn't text.\n",{"id":5935,"difficulty":63,"q":5936,"a":5937},"pathlib-vs-os-path","What is pathlib.Path and how does it compare to os.path?","**`pathlib.Path`** is the modern, object-oriented way to handle filesystem paths. A\n`Path` is an object with **methods and operators**, whereas the older **`os.path`**\nmodule is a collection of **string-based functions**. Path's `\u002F` operator joins\nsegments cleanly and works across operating systems.\n\n```python\nfrom pathlib import Path\n\np = Path(\"data\") \u002F \"logs\" \u002F \"app.log\"   # join with \u002F\np.exists()\np.suffix                                 # \".log\"\np.stem                                   # \"app\"\np.read_text(encoding=\"utf-8\")            # one-liner read\n\nimport os.path\nold = os.path.join(\"data\", \"logs\", \"app.log\")\nos.path.exists(old)\n```\n\n`pathlib` is generally preferred for new code: it's more readable and bundles\ncommon operations (`read_text`, `mkdir`, `glob`) as methods. Use `os.path` mainly\nwhen working with existing string-based APIs.\n",{"id":5939,"difficulty":63,"q":5940,"a":5941},"globbing-path-methods","How do you find files with globbing using pathlib?","Use **`Path.glob(pattern)`** for matches in one directory and **`Path.rglob(pattern)`**\n(or `glob(\"**\u002F...\")`) to recurse into subdirectories. Both return a **lazy generator**\nof `Path` objects, where `*` matches any characters and `**` matches directories\nrecursively.\n\n```python\nfrom pathlib import Path\n\nroot = Path(\"project\")\nfor py in root.glob(\"*.py\"):         # top level only\n    print(py.name)\n\nfor py in root.rglob(\"*.py\"):        # all subdirectories too\n    print(py)\n\nroot.mkdir(parents=True, exist_ok=True)  # create dirs safely\n[p.name for p in root.iterdir()]         # list directory contents\n```\n\nOther handy `Path` methods: `iterdir()` (list a directory), `is_file()`\u002F`is_dir()`,\n`mkdir()`, `unlink()` (delete), and `with_suffix()`. Globbing returns generators, so\nwrap in `list(...)` if you need a concrete collection.\n",{"description":61},"Python interview questions on open() and the with statement, lazy file iteration, text vs binary mode and encoding, pathlib.Path vs os.path, and globbing.","python\u002Fstdlib\u002Ffiles-pathlib","Files, pathlib & os","NoZp_VMdm_N8l_uZ9iKq2ZIl7xuq4gVgtZ6dt2hEatE",{"id":5948,"title":5949,"body":5950,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5954,"navigation":66,"order":12,"path":5955,"questions":5956,"related":207,"seo":5977,"seoDescription":5978,"stem":5979,"subtopic":5980,"topic":5909,"topicSlug":5910,"updated":214,"__hash__":5981},"qa\u002Fpython\u002Fstdlib\u002Fregex.md","Regex",{"type":58,"value":5951,"toc":5952},[],{"title":61,"searchDepth":22,"depth":22,"links":5953},[],{},"\u002Fpython\u002Fstdlib\u002Fregex",[5957,5961,5965,5969,5973],{"id":5958,"difficulty":71,"q":5959,"a":5960},"match-search-fullmatch","What is the difference between re.match, re.search, and re.fullmatch?","They differ in **where** the pattern must match. `re.match` anchors at the\n**start** of the string (but not the end). `re.search` scans for the pattern\n**anywhere** in the string. `re.fullmatch` requires the pattern to match the\n**entire** string. All return a `Match` object on success or `None` on failure.\n\n```python\nimport re\nre.match(\"ab\", \"abcd\")      # match — starts with 'ab'\nre.match(\"cd\", \"abcd\")      # None  — not at the start\nre.search(\"cd\", \"abcd\")     # match — found anywhere\nre.fullmatch(\"ab\", \"abcd\")  # None  — must match the whole string\nre.fullmatch(\"abcd\", \"abcd\")# match\n```\n\nA common bug is using `match` expecting whole-string validation — it only\nanchors the start. Rule of thumb: use `search` to find, `fullmatch` to\nvalidate, and `match` only when you specifically mean \"begins with\".\n",{"id":5962,"difficulty":63,"q":5963,"a":5964},"groups-named-groups","How do capture groups and named groups work?","Parentheses `( )` create a **capture group** you retrieve by **number**\n(1-based; group 0 is the whole match). `(?P\u003Cname>...)` creates a **named\ngroup** you retrieve by name — far more readable. `(?:...)` groups **without\ncapturing** when you only need it for grouping\u002Falternation.\n\n```python\nimport re\nm = re.search(r\"(\\d{4})-(\\d{2})\", \"2026-06\")\nm.group(0)   # '2026-06'  — whole match\nm.group(1)   # '2026'     — first group\nm.groups()   # ('2026', '06')\n\nm = re.search(r\"(?P\u003Cyear>\\d{4})-(?P\u003Cmonth>\\d{2})\", \"2026-06\")\nm.group(\"year\")   # '2026'\nm.groupdict()     # {'year': '2026', 'month': '06'}\n```\n\nNamed groups make patterns self-documenting and resilient to reordering.\nRule of thumb: use `(?P\u003Cname>...)` for anything you'll extract, and\n`(?:...)` when grouping is structural only.\n",{"id":5966,"difficulty":63,"q":5967,"a":5968},"re-compile-why","What does re.compile do, and why would you use it?","`re.compile(pattern)` builds a **reusable pattern object** once, then you call\nmethods (`.search`, `.match`, `.findall`, `.sub`) on it. The module-level\nfunctions actually compile internally and **cache** recent patterns, so the\nmain win is **clarity and reuse** — plus a small speedup when a pattern is\nused **many times in a loop**.\n\n```python\nimport re\nDATE = re.compile(r\"(?P\u003Cyear>\\d{4})-(?P\u003Cmonth>\\d{2})\")  # compile once\n\nfor line in lines:\n    m = DATE.search(line)   # reuse the compiled object\n    if m:\n        print(m.group(\"year\"))\n```\n\nIt also lets you attach **flags** (e.g. `re.IGNORECASE`, `re.VERBOSE`) in one\nplace. Rule of thumb: compile patterns used repeatedly or shared across a\nmodule; for one-off use the module functions are fine.\n",{"id":5970,"difficulty":84,"q":5971,"a":5972},"greedy-vs-lazy","What is the difference between greedy and non-greedy matching?","By default quantifiers (`*`, `+`, `?`, `{m,n}`) are **greedy** — they match as\n**much** as possible, then backtrack. Adding a trailing `?` makes them\n**non-greedy** (lazy) — they match as **little** as possible. This matters\nhugely when a delimiter can appear multiple times.\n\n```python\nimport re\ntext = \"\u003Ca>\u003Cb>\"\nre.search(r\"\u003C.*>\", text).group()    # '\u003Ca>\u003Cb>'  — greedy, grabs everything\nre.search(r\"\u003C.*?>\", text).group()   # '\u003Ca>'     — lazy, stops at first '>'\n```\n\nGreedy patterns over-matching is a classic \"regex ate too much\" bug. Rule of\nthumb: when matching content **between delimiters**, reach for the lazy `*?`\n\u002F `+?` (or a negated character class like `[^>]*`).\n",{"id":5974,"difficulty":63,"q":5975,"a":5976},"re-sub-raw-strings","How does re.sub work, and why use raw strings for patterns?","`re.sub(pattern, repl, string)` returns a **new** string with all matches\nreplaced. The replacement can reference captured groups with `\\1` or\n`\\g\u003Cname>`, or be a **function** that receives each `Match` for dynamic\nreplacement. You should write patterns as **raw strings** (`r\"...\"`) so that\nbackslash escapes like `\\d` and `\\b` reach the regex engine instead of being\ninterpreted by Python first.\n\n```python\nimport re\nre.sub(r\"\\s+\", \" \", \"a   b\\tc\")          # 'a b c'  — collapse whitespace\nre.sub(r\"(\\d{4})-(\\d{2})\", r\"\\2\u002F\\1\", \"2026-06\")  # '06\u002F2026' — reorder groups\nre.sub(r\"\\d+\", lambda m: f\"[{m.group()}]\", \"x9\")  # 'x[9]' — function repl\n\n\"\\d\"     # in a normal string this is an invalid escape (warns)\nr\"\\d\"    # raw string — passes \\d straight to the engine\n```\n\nWithout `r\"\"`, `\"\\b\"` becomes a backspace character, not a word boundary —\na subtle, hard-to-spot bug. Rule of thumb: **always** prefix regex patterns\nwith `r`.\n",{"description":61},"Python interview questions on the re module — match vs search vs fullmatch, capture and named groups, re.compile, greedy vs non-greedy, re.sub, and raw strings.","python\u002Fstdlib\u002Fregex","Regular Expressions","tGHa2xgx5-BCvqtnwBZ867ytagB6ZPf257IKaZ2rmW0",{"id":5983,"title":5984,"body":5985,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":5989,"navigation":66,"order":40,"path":5990,"questions":5991,"related":207,"seo":6012,"seoDescription":6013,"stem":6014,"subtopic":6015,"topic":5909,"topicSlug":5910,"updated":214,"__hash__":6016},"qa\u002Fpython\u002Fstdlib\u002Fserialization.md","Serialization",{"type":58,"value":5986,"toc":5987},[],{"title":61,"searchDepth":22,"depth":22,"links":5988},[],{},"\u002Fpython\u002Fstdlib\u002Fserialization",[5992,5996,6000,6004,6008],{"id":5993,"difficulty":71,"q":5994,"a":5995},"json-dumps-loads","How do json.dumps and json.loads work, and how do Python types map to JSON?","**`json.dumps`** serializes a Python object **to** a JSON string; **`json.loads`**\nparses a JSON string **back** into Python objects. The `dump`\u002F`load` variants\n(no `s`) work with file objects instead. The conversion follows a fixed type\nmapping.\n\n```python\nimport json\n\ndata = {\"name\": \"Ada\", \"age\": 36, \"tags\": [\"math\"], \"active\": True}\ns = json.dumps(data)            # dict -> JSON string\nback = json.loads(s)            # JSON string -> dict\n\nwith open(\"out.json\", \"w\") as f:\n    json.dump(data, f)          # write to file\n```\n\nThe mapping: `dict`->object, `list`\u002F`tuple`->array, `str`->string, `int`\u002F`float`\n->number, `True`\u002F`False`->`true`\u002F`false`, `None`->`null`. Note **tuples become\narrays** (you get a list back), and **dict keys are coerced to strings**. JSON has\nno native date, set, or bytes type.\n",{"id":5997,"difficulty":63,"q":5998,"a":5999},"json-custom-encoding","How do you serialize an object JSON doesn't support by default?","Unsupported types raise `TypeError: ... is not JSON serializable`. The two standard\nfixes are the **`default=` callback** (a function called for any unserializable\nobject, returning a JSON-friendly substitute) or a custom **`JSONEncoder` subclass**\npassed via **`cls=`**.\n\n```python\nimport json\nfrom datetime import datetime\n\ndef encode(obj):\n    if isinstance(obj, datetime):\n        return obj.isoformat()        # turn it into a string\n    raise TypeError(f\"not serializable: {type(obj)}\")\n\njson.dumps({\"when\": datetime.now()}, default=encode)\n\nclass MyEncoder(json.JSONEncoder):    # the class-based alternative\n    def default(self, obj):\n        if isinstance(obj, set):\n            return list(obj)\n        return super().default(obj)\njson.dumps({1, 2, 3}, cls=MyEncoder)\n```\n\nUse `default=` for a quick one-off; subclass `JSONEncoder` when you want reusable\nencoding logic. On the way back, use `object_hook` in `loads` to reconstruct custom\ntypes.\n",{"id":6001,"difficulty":63,"q":6002,"a":6003},"csv-reader-dictreader","What is the difference between csv.reader and csv.DictReader?","Both read CSV files, but the row format differs. **`csv.reader`** yields each row as\na **list of strings** indexed by position. **`csv.DictReader`** treats the first row\nas **headers** and yields each row as a **dict** keyed by column name — far more\nreadable and robust to column reordering.\n\n```python\nimport csv\n\nwith open(\"people.csv\", newline=\"\") as f:\n    for row in csv.reader(f):\n        print(row[0], row[1])         # positional — brittle\n\nwith open(\"people.csv\", newline=\"\") as f:\n    for row in csv.DictReader(f):\n        print(row[\"name\"], row[\"age\"])  # by header — clear\n```\n\nAlways open CSV files with **`newline=\"\"`** to let the `csv` module handle line\nendings correctly. Prefer `DictReader`\u002F`DictWriter` for named-column access; use the\nplain `reader` for headerless or purely positional data.\n",{"id":6005,"difficulty":63,"q":6006,"a":6007},"pickle-vs-json","What is the difference between pickle and json, and what is the security warning?","**`json`** is a **text**, language-independent format for **simple data** (dicts,\nlists, numbers, strings). **`pickle`** is a **binary**, Python-specific format that\ncan serialize **almost any Python object** (custom classes, functions references,\nnested objects). The crucial caveat: **never unpickle untrusted data**.\n\n```python\nimport json, pickle\n\njson.dumps({\"x\": 1})              # \"{\\\"x\\\": 1}\" — readable, portable\npickle.dumps({\"x\": 1})            # b'\\x80\\x04...' — binary, Python-only\n\n# DANGER: unpickling runs arbitrary code embedded in the data\npickle.loads(untrusted_bytes)     # can execute malicious payloads!\n```\n\n`pickle.loads` can **execute arbitrary code** during deserialization, so it's a\nremote-code-execution risk on attacker-controlled input. Rule of thumb: use **json**\nfor config, APIs, and anything crossing a trust boundary; use **pickle** only for\ntrusted, internal Python-to-Python data (e.g. caches you wrote yourself).\n",{"id":6009,"difficulty":63,"q":6010,"a":6011},"serializing-datetimes","How do you serialize datetimes to JSON and back?","JSON has **no date type**, so a `datetime` must be converted to a **string** — the\nISO 8601 format via **`.isoformat()`** is the standard choice because it's\nunambiguous and parseable. On the way out use `default=`; on the way back parse the\nstring with `datetime.fromisoformat()`.\n\n```python\nimport json\nfrom datetime import datetime\n\nevent = {\"name\": \"launch\", \"at\": datetime(2026, 6, 18, 14, 30)}\n\ntext = json.dumps(event, default=lambda o: o.isoformat())\n# '{\"name\": \"launch\", \"at\": \"2026-06-18T14:30:00\"}'\n\nraw = json.loads(text)\nraw[\"at\"] = datetime.fromisoformat(raw[\"at\"])   # back to datetime\n```\n\nJSON can't tell a date-string from an ordinary string, so you must know which fields\nto re-parse (or use `object_hook`). Prefer ISO strings in **UTC** for portability,\nand convert to local time only at display.\n",{"description":61},"Python interview questions on json.dumps\u002Floads and type mapping, custom JSON encoding, csv reader vs DictReader, pickle vs json and pickle security, and serializing datetimes.","python\u002Fstdlib\u002Fserialization","JSON, CSV & pickle","viTtNO-ARfmO9ag13muRGsYBkN9JO5C_NMhcGlPbP1U",{"id":6018,"title":6019,"body":6020,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":6024,"navigation":66,"order":22,"path":6025,"questions":6026,"related":207,"seo":6051,"seoDescription":6052,"stem":6053,"subtopic":6054,"topic":6055,"topicSlug":6056,"updated":214,"__hash__":6057},"qa\u002Fpython\u002Ftesting\u002Fmocking.md","Mocking",{"type":58,"value":6021,"toc":6022},[],{"title":61,"searchDepth":22,"depth":22,"links":6023},[],{},"\u002Fpython\u002Ftesting\u002Fmocking",[6027,6031,6035,6039,6043,6047],{"id":6028,"difficulty":71,"q":6029,"a":6030},"what-is-mocking","What is mocking and why do you use it?","**Mocking** replaces a real dependency with a **fake stand-in object** that records\nhow it was called and returns whatever you tell it to. You use it to **isolate the\ncode under test** from slow, unreliable, or side-effecting collaborators — network\ncalls, databases, the clock, third-party APIs.\n\n```python\nfrom unittest.mock import Mock\n\nservice = Mock()\nservice.fetch.return_value = {\"id\": 1}    # canned response\n\nresult = service.fetch(\"\u002Fusers\u002F1\")        # no real network call\nresult                                    # {\"id\": 1}\nservice.fetch.assert_called_once()        # verify it happened\n```\n\nMocking makes tests **fast, deterministic, and focused** on your logic rather than\nthe dependency's. Rule of thumb: mock at the **boundaries** of your system (I\u002FO,\nexternal services), not your own pure functions.\n",{"id":6032,"difficulty":63,"q":6033,"a":6034},"mock-vs-magicmock","What is the difference between Mock and MagicMock?","Both auto-create attributes and methods on access. The difference: **`MagicMock`**\nadditionally supports **magic (dunder) methods** — `__len__`, `__iter__`,\n`__getitem__`, `__enter__`\u002F`__exit__`, etc. — so it can stand in for objects used\nwith `len()`, iteration, indexing, or `with`. A plain **`Mock`** raises on dunder\naccess.\n\n```python\nfrom unittest.mock import Mock, MagicMock\n\nm = Mock()\nlen(m)                  # TypeError — Mock has no __len__\n\nmm = MagicMock()\nmm.__len__.return_value = 3\nlen(mm)                 # 3 — magic methods supported\nlist(mm)                # works — __iter__ is mocked too\n```\n\n`patch()` uses `MagicMock` by default, which is why patched objects \"just work\" in\nmost cases. Use `MagicMock` when the dependency relies on protocols\u002Fdunders; `Mock`\nis fine for plain method calls.\n",{"id":6036,"difficulty":84,"q":6037,"a":6038},"patch-where-used","How does unittest.mock.patch work, and what does \"patch where it's used\" mean?","**`patch`** temporarily replaces an object with a mock for the duration of a test,\nas a **decorator** or a **context manager**, restoring the original afterward. The\ncritical rule is **\"patch where it's looked up, not where it's defined\"** — you patch\nthe name in the **module that imports and uses it**.\n\n```python\n# app.py\nfrom time import time\ndef stamp(): return time()\n\n# test.py — patch the reference INSIDE app, not 'time.time'\nfrom unittest.mock import patch\n\n@patch(\"app.time\")                 # where it's USED\ndef test_stamp(mock_time):\n    mock_time.return_value = 123\n    assert stamp() == 123\n\nwith patch(\"app.time\") as mock_time:   # context-manager form\n    mock_time.return_value = 123\n```\n\nPatching `\"time.time\"` here would fail, because `app` already bound its own `time`\nname at import. Always target the **importing module's namespace** — this is the\nsingle most common mocking mistake.\n",{"id":6040,"difficulty":63,"q":6041,"a":6042},"return-value-side-effect","What is the difference between return_value and side_effect?","**`return_value`** sets a **single fixed value** the mock returns on every call.\n**`side_effect`** is more powerful: assign a **function** (called with the same args),\nan **exception** (which gets raised), or an **iterable** (returning a different value\nper successive call).\n\n```python\nfrom unittest.mock import Mock\n\nm = Mock(return_value=42)\nm(); m()                       # 42, 42 — always the same\n\nm.side_effect = [1, 2, 3]      # one per call\nm(); m()                       # 1, then 2\n\nm.side_effect = ValueError(\"boom\")\nm()                            # raises ValueError\n\nm.side_effect = lambda x: x * 2\nm(10)                          # 20 — computed from the arg\n```\n\nUse `return_value` for a constant stub, and `side_effect` to **raise errors**,\n**vary results across calls**, or **compute** based on arguments. If both are set,\n`side_effect` wins (unless it returns the sentinel `DEFAULT`).\n",{"id":6044,"difficulty":63,"q":6045,"a":6046},"call-assertions","How do you assert a mock was called correctly?","Mocks **record every call**, so you verify interactions with the `assert_called*`\nfamily. Check **whether\u002Fhow many times** it was called and **with what arguments**,\nand inspect history via `call_args` \u002F `call_args_list`.\n\n```python\nfrom unittest.mock import Mock, call\n\nm = Mock()\nm(1, 2)\nm(3, key=\"v\")\n\nm.assert_called()                       # at least once\nm.assert_called_once()                  # exactly once -> would FAIL here\nm.assert_called_with(3, key=\"v\")        # the MOST RECENT call\nm.assert_any_call(1, 2)                 # any call matched\nm.assert_has_calls([call(1, 2), call(3, key=\"v\")])\nm.call_count                            # 2\n```\n\nNote `assert_called_with` checks only the **last** call — use `assert_any_call` or\n`assert_has_calls` for earlier ones. Beware typos: a misspelled assertion (e.g.\n`assert_called_once_with` -> `assert_called_onced_with`) silently passes, so spell\nthese carefully.\n",{"id":6048,"difficulty":63,"q":6049,"a":6050},"autospec","What is autospec and why is it useful?","A normal mock accepts **any** attribute access or call signature, so it can hide bugs\n— a test passes even if you call a method that doesn't exist or with wrong arguments.\n**Autospec** (`autospec=True`, or `create_autospec`) builds the mock to **match the\nreal object's API**, so it rejects nonexistent attributes and mismatched signatures.\n\n```python\nfrom unittest.mock import patch, create_autospec\n\nclass Api:\n    def fetch(self, url): ...\n\n@patch(\"app.Api\", autospec=True)\ndef test_it(MockApi):\n    api = MockApi()\n    api.fetch(\"\u002Fx\")          # OK — matches real signature\n    api.fetch()              # TypeError — missing 'url'!\n    api.delete()             # AttributeError — no such method\n```\n\nAutospec makes mocks **stay in sync with the real interface**, catching drift when\nthe real API changes. The tradeoff is a small overhead, but it's strongly\nrecommended for non-trivial dependencies.\n",{"description":61},"Python interview questions on mocking and why it matters, Mock vs MagicMock, unittest.mock.patch and patching where it's used, return_value vs side_effect, call assertions, and autospec.","python\u002Ftesting\u002Fmocking","Mocking & Patching","Testing","testing","BuZRYss6gdlr3knpMQwWz6MR4-fuMtldIPIpMqBQI_4",{"id":6059,"title":6060,"body":6061,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":6065,"navigation":66,"order":12,"path":6066,"questions":6067,"related":207,"seo":6092,"seoDescription":6093,"stem":6094,"subtopic":6095,"topic":6055,"topicSlug":6056,"updated":214,"__hash__":6096},"qa\u002Fpython\u002Ftesting\u002Fpytest.md","Pytest",{"type":58,"value":6062,"toc":6063},[],{"title":61,"searchDepth":22,"depth":22,"links":6064},[],{},"\u002Fpython\u002Ftesting\u002Fpytest",[6068,6072,6076,6080,6084,6088],{"id":6069,"difficulty":71,"q":6070,"a":6071},"pytest-vs-unittest","What is the difference between pytest and unittest?","**`unittest`** is the **standard-library** framework, modeled on xUnit: tests\nare **methods on a `TestCase` subclass** and you use `self.assertEqual`,\n`self.assertTrue`, etc. **`pytest`** is a **third-party** framework that runs\nplain functions using the bare `assert` statement, with rich failure\nintrospection, fixtures, and `parametrize`.\n\n```python\n# unittest\nimport unittest\nclass TestMath(unittest.TestCase):\n    def test_add(self):\n        self.assertEqual(1 + 1, 2)\n\n# pytest — just a function and assert\ndef test_add():\n    assert 1 + 1 == 2\n```\n\npytest can also **run existing unittest tests**, so adopting it is low-risk.\nRule of thumb: prefer pytest for new code — less boilerplate and better\noutput — while unittest is fine when you must avoid dependencies.\n",{"id":6073,"difficulty":63,"q":6074,"a":6075},"fixtures-scope","What are pytest fixtures, and what does scope control?","A **fixture** is a function decorated with `@pytest.fixture` that provides\n**setup (and teardown) for tests**. A test requests it simply by naming it as\na **parameter**, and pytest injects the return value. Using `yield` lets code\nafter the `yield` run as **teardown**. The **`scope`** controls how often the\nfixture is created: `function` (default), `class`, `module`, or `session`.\n\n```python\nimport pytest\n\n@pytest.fixture(scope=\"module\")   # created once per module\ndef db():\n    conn = connect()\n    yield conn                    # value handed to tests\n    conn.close()                  # teardown after tests finish\n\ndef test_query(db):               # db injected by name\n    assert db.ping()\n```\n\nWider scopes share expensive resources (DB connections, servers) across many\ntests for speed; narrower scopes give better **isolation**. Rule of thumb:\ndefault to `function` scope and only widen when setup is costly.\n",{"id":6077,"difficulty":63,"q":6078,"a":6079},"parametrize","How does @pytest.mark.parametrize work?","`@pytest.mark.parametrize` runs the **same test function multiple times** with\ndifferent arguments, generating **one separate test case per row**. Each case\npasses or fails independently, so a single bad input doesn't hide the others —\nfar cleaner than a loop inside one test.\n\n```python\nimport pytest\n\n@pytest.mark.parametrize(\"value, expected\", [\n    (2, 4),\n    (3, 9),\n    (4, 16),\n])\ndef test_square(value, expected):\n    assert value ** 2 == expected\n```\n\npytest reports each as `test_square[2-4]`, `test_square[3-9]`, etc., and you\ncan stack decorators to get the **cross product** of inputs. Rule of thumb:\nuse `parametrize` for the same logic across many inputs instead of copy-pasted\ntests or in-test loops.\n",{"id":6081,"difficulty":84,"q":6082,"a":6083},"mocking-monkeypatch","How do you mock with monkeypatch versus unittest.mock?","The built-in **`monkeypatch`** fixture **replaces attributes, dict items, or\nenv vars** for the duration of a test and **auto-restores** them afterward —\nideal for swapping out a function or setting `os.environ`. **`unittest.mock`**\n(`Mock`, `patch`) creates **mock objects** that record calls and let you set\nreturn values or side effects — best when you need to **assert how** a\ndependency was called.\n\n```python\nimport requests, mymodule\n\ndef test_with_monkeypatch(monkeypatch):\n    monkeypatch.setattr(requests, \"get\", lambda url: {\"ok\": True})\n    assert mymodule.fetch() == {\"ok\": True}\n\nfrom unittest.mock import patch\ndef test_with_mock():\n    with patch(\"mymodule.requests.get\") as mock_get:\n        mock_get.return_value = {\"ok\": True}\n        mymodule.fetch()\n        mock_get.assert_called_once()   # verify the interaction\n```\n\nA key gotcha: **patch where the name is looked up** (`mymodule.requests.get`),\nnot where it's defined. Rule of thumb: `monkeypatch` for simple replacements,\n`unittest.mock` when you need to **inspect calls**.\n",{"id":6085,"difficulty":63,"q":6086,"a":6087},"pytest-raises","How do you assert that code raises an exception?","Use the **`pytest.raises`** context manager: the test **passes only if** the\nexpected exception is raised inside the `with` block, and **fails** if no\nexception (or the wrong one) occurs. You can capture the exception via\n`as excinfo` to assert on its message, and use `match=` for a regex check.\n\n```python\nimport pytest\n\ndef test_divide_by_zero():\n    with pytest.raises(ZeroDivisionError):\n        1 \u002F 0\n\ndef test_message():\n    with pytest.raises(ValueError, match=\"invalid\"):\n        int(\"not a number\")   # ValueError: invalid literal...\n    # or: assert \"invalid\" in str(excinfo.value)\n```\n\nIt cleanly replaces a `try\u002Fexcept\u002Fpytest.fail` dance. Rule of thumb: always\nassert on the **specific** exception type (and ideally the message) so the\ntest can't pass for the wrong reason.\n",{"id":6089,"difficulty":63,"q":6090,"a":6091},"conftest","What is conftest.py used for?","**`conftest.py`** is a special pytest file for **shared fixtures and hooks**.\npytest **auto-discovers** it — no import needed — and any fixture defined\nthere is **available to every test** in that directory and its subdirectories.\nIt's the standard place to put fixtures used across multiple test files.\n\n```python\n# tests\u002Fconftest.py\nimport pytest\n\n@pytest.fixture\ndef client():\n    return create_test_client()\n\n# tests\u002Ftest_users.py — no import required\ndef test_login(client):           # 'client' resolved from conftest\n    assert client.login(\"ada\")\n```\n\nYou can also register plugins, define hooks like `pytest_addoption`, and place\na `conftest.py` at multiple levels for **scoped** sharing. Rule of thumb: put\na fixture in `conftest.py` once more than one test file needs it, instead of\nimporting it around.\n",{"description":61},"Python interview questions on pytest — pytest vs unittest, fixtures and scope, parametrize, mocking with monkeypatch and unittest.mock, pytest.raises, and conftest.py.","python\u002Ftesting\u002Fpytest","pytest Essentials","k9bgHlANacbZ5kAs3vq6F-kv1RDc9uTZZ6pHwnijVHI",{"id":6098,"title":6099,"body":6100,"description":61,"difficulty":84,"extension":64,"framework":30,"frameworkSlug":28,"meta":6104,"navigation":66,"order":22,"path":6105,"questions":6106,"related":207,"seo":6131,"seoDescription":6132,"stem":6133,"subtopic":6134,"topic":6135,"topicSlug":6136,"updated":214,"__hash__":6137},"qa\u002Fpython\u002Ftyping\u002Fgenerics-protocols.md","Generics Protocols",{"type":58,"value":6101,"toc":6102},[],{"title":61,"searchDepth":22,"depth":22,"links":6103},[],{},"\u002Fpython\u002Ftyping\u002Fgenerics-protocols",[6107,6111,6115,6119,6123,6127],{"id":6108,"difficulty":84,"q":6109,"a":6110},"typevar-generic","What are TypeVar and Generic, and how do you write a generic class?","A **`TypeVar`** is a type variable — a placeholder that lets a function or class\nwork with **any type while preserving it** across inputs and outputs. Subclassing\n**`Generic[T]`** turns a class into a generic container parameterized by that\nvariable, so a `Stack[int]` is known to hold and return `int`s.\n\n```python\nfrom typing import TypeVar, Generic\n\nT = TypeVar(\"T\")               # one placeholder type\n\ndef first(items: list[T]) -> T:  # in and out share T\n    return items[0]\n\nclass Stack(Generic[T]):       # generic class\n    def __init__(self) -> None:\n        self._items: list[T] = []\n    def push(self, x: T) -> None:\n        self._items.append(x)\n    def pop(self) -> T:\n        return self._items.pop()\n\ns: Stack[int] = Stack()\ns.push(1)\nn = s.pop()                    # type checker knows n is int\n```\n\nUse a `TypeVar` whenever a relationship between argument and return types must be\ncaptured — `def first(items: list) -> object` loses that, but `list[T] -> T`\nkeeps it. In Python 3.12+ you can write `def first[T](items: list[T]) -> T`\nwithout the explicit `TypeVar`.\n",{"id":6112,"difficulty":84,"q":6113,"a":6114},"bounded-typevar","What is a bounded or constrained TypeVar?","A plain `TypeVar` accepts **any** type. A **bound** (`bound=...`) restricts it to a\ntype **and its subclasses**, while **constraints** (`TypeVar(\"T\", int, str)`)\nrestrict it to a fixed set of specific types. Both let the body safely use the\ncapabilities implied by the bound.\n\n```python\nfrom typing import TypeVar\n\nclass Animal:\n    def speak(self) -> str: ...\n\nA = TypeVar(\"A\", bound=Animal)     # A must be Animal or a subclass\n\ndef loudest(animals: list[A]) -> A:\n    for a in animals:\n        a.speak()                  # OK — bound guarantees this method\n    return animals[0]\n\nNum = TypeVar(\"Num\", int, float)   # constrained: ONLY int or float\ndef double(x: Num) -> Num:\n    return x * 2\n```\n\nReach for a **bound** when \"any subtype of X\" is acceptable and the body needs X's\ninterface; use **constraints** when only a handful of unrelated concrete types\nshould be allowed.\n",{"id":6116,"difficulty":84,"q":6117,"a":6118},"protocol-structural","What is typing.Protocol and how does it enable structural typing?","A **`Protocol`** defines an interface by **shape** rather than inheritance: any\nobject that has the right methods\u002Fattributes is accepted, even if it never\nexplicitly subclasses the protocol. This is **structural typing** (\"duck typing\")\nchecked statically — \"if it walks like a duck.\"\n\n```python\nfrom typing import Protocol\n\nclass SupportsClose(Protocol):\n    def close(self) -> None: ...\n\ndef shutdown(resource: SupportsClose) -> None:\n    resource.close()\n\nclass File:                # never inherits SupportsClose...\n    def close(self) -> None: ...\n\nshutdown(File())           # ...but accepted: it has close()\n```\n\nContrast with **nominal typing** (the usual `class B(A)`), where you must declare the\nrelationship. Protocols decouple the consumer from concrete classes — great for\ntyping third-party objects you can't modify.\n",{"id":6120,"difficulty":63,"q":6121,"a":6122},"runtime-checkable","What does @runtime_checkable do for a Protocol?","By default a `Protocol` exists only for **static** checkers — `isinstance()` against\nit raises `TypeError`. Decorating it with **`@runtime_checkable`** allows\n`isinstance()` \u002F `issubclass()` checks at runtime, but only for the **presence of\nthe named methods**, not their signatures or return types.\n\n```python\nfrom typing import Protocol, runtime_checkable\n\n@runtime_checkable\nclass Sized(Protocol):\n    def __len__(self) -> int: ...\n\nisinstance([1, 2, 3], Sized)   # True  — list has __len__\nisinstance(42, Sized)          # False — int has no __len__\n```\n\nIt's a convenience, not a guarantee: the check confirms a method *exists*, not that\nit takes the right arguments. Prefer static checking; use `@runtime_checkable` only\nwhen you genuinely need a runtime branch.\n",{"id":6124,"difficulty":63,"q":6125,"a":6126},"callable-types","How do you type a function passed as an argument?","Use **`Callable[[ArgTypes], ReturnType]`** from `typing` (or the built-in\n`collections.abc.Callable`). The first element is the **list of parameter types**,\nthe second is the **return type**. Use `...` for the parameters when you want to\naccept any signature.\n\n```python\nfrom collections.abc import Callable\n\ndef apply(fn: Callable[[int, int], int], a: int, b: int) -> int:\n    return fn(a, b)\n\napply(lambda x, y: x + y, 2, 3)        # 5\n\nhandler: Callable[..., None]           # any args, returns None\nno_args: Callable[[], str]             # takes nothing, returns str\n```\n\nFor more precise signatures (preserving exact parameters of a wrapped function),\n`ParamSpec` exists, but `Callable[[...], R]` covers the common cases. Type your\ncallbacks so the checker catches mismatched handlers.\n",{"id":6128,"difficulty":84,"q":6129,"a":6130},"covariance-invariance","What is the difference between covariance and invariance in generics?","Variance describes whether `Container[Subtype]` is usable where `Container[Supertype]`\nis expected. **Invariant** (the default, e.g. `list[T]`): `list[int]` is **not** a\n`list[str]` *or* a `list[object]`. **Covariant**: `Tuple[int]` is acceptable as\n`Tuple[object]`. The intuition: **mutable** containers must be invariant for safety;\n**read-only** ones can be covariant.\n\n```python\ndef total(nums: list[float]) -> float: ...\nints: list[int] = [1, 2]\ntotal(ints)        # type ERROR — list is invariant\n\nfrom collections.abc import Sequence\ndef total2(nums: Sequence[float]) -> float: ...\ntotal2(ints)       # OK — Sequence is covariant (read-only)\n```\n\nWhy mutables are invariant: if `list[int]` were a `list[object]`, a function could\nappend a `str` to it, corrupting the original `list[int]`. Rule of thumb: accept\n**`Sequence`\u002F`Iterable`** (covariant, read-only) in parameters to be flexible; reserve\n`list`\u002F`dict` for when you truly need to mutate.\n",{"description":61},"Python interview questions on TypeVar and Generic classes, bounded type variables, typing.Protocol structural typing, Callable types, and covariance vs invariance.","python\u002Ftyping\u002Fgenerics-protocols","Generics & Protocols","Type Hints & Typing","typing","tqB3wOAZgFxlWwfX7xtXC5pu1C_ZvRqITJYDLjrlBbc",{"id":6139,"title":6140,"body":6141,"description":61,"difficulty":63,"extension":64,"framework":30,"frameworkSlug":28,"meta":6145,"navigation":66,"order":12,"path":6146,"questions":6147,"related":207,"seo":6168,"seoDescription":6169,"stem":6170,"subtopic":6171,"topic":6135,"topicSlug":6136,"updated":214,"__hash__":6172},"qa\u002Fpython\u002Ftyping\u002Ftype-hints.md","Type Hints",{"type":58,"value":6142,"toc":6143},[],{"title":61,"searchDepth":22,"depth":22,"links":6144},[],{},"\u002Fpython\u002Ftyping\u002Ftype-hints",[6148,6152,6156,6160,6164],{"id":6149,"difficulty":71,"q":6150,"a":6151},"hints-runtime-enforced","Are type hints enforced at runtime?","**No.** Type hints are **annotations**, not constraints — the interpreter\nstores them (in `__annotations__`) but **never checks them**. You can pass\na `str` where an `int` is annotated and Python runs it happily; enforcement\nis the job of an **external static type checker** like **mypy** or **pyright**.\n\n```python\ndef double(n: int) -> int:\n    return n * 2\n\ndouble(\"ab\")          # runs fine -> \"abab\", no TypeError\ndouble.__annotations__  # {'n': \u003Cclass 'int'>, 'return': \u003Cclass 'int'>}\n```\n\nIf you want runtime validation you opt in explicitly — e.g. **pydantic**,\n`typing.get_type_hints`, or manual `isinstance` checks. Rule of thumb: hints\ndocument and enable tooling; they are **not** a runtime guard.\n",{"id":6153,"difficulty":63,"q":6154,"a":6155},"optional-union","What is the difference between Optional, Union, and the `|` operator?","`Union[A, B]` means \"**A or B**\". `Optional[X]` is just shorthand for\n`Union[X, None]` — a value that may be `X` **or** `None`. It does **not**\nmean \"optional argument\"; it means \"could be None\". Since Python 3.10 you\ncan write unions with the **`|` operator** instead of importing from `typing`.\n\n```python\nfrom typing import Optional, Union\n\ndef find(id: int) -> Optional[str]: ...     # str or None\ndef parse(x: Union[int, str]) -> int: ...   # int or str\n\n# Python 3.10+ equivalent, no imports:\ndef find(id: int) -> str | None: ...\ndef parse(x: int | str) -> int: ...\n```\n\nPrefer the modern `X | None` syntax on 3.10+. Reach for `Optional`\u002F`Union`\nfrom `typing` only when supporting older versions. Rule of thumb: `Optional`\nis about **nullability**, never about whether a parameter has a default.\n",{"id":6157,"difficulty":63,"q":6158,"a":6159},"list-vs-generics","What is the difference between `list` and `List`, and how do generics work?","Both annotate a list, but **`List` comes from `typing`** while **`list`** is\nthe built-in. Since **Python 3.9** the built-in containers are themselves\n**subscriptable** (`list[int]`, `dict[str, int]`), so `typing.List`,\n`typing.Dict`, etc. are **deprecated** — use the lowercase built-ins. A bare\n`list` means \"list of anything\"; the **generic** form pins the element type.\n\n```python\nfrom typing import List          # legacy\nnames: List[str] = []\n\nnames: list[str] = []            # modern (3.9+), preferred\nscores: dict[str, int] = {}\npair: tuple[int, str] = (1, \"a\")\n```\n\nGenerics let a checker verify element access and method calls. Rule of thumb:\non 3.9+ always parameterize the **built-in** (`list[str]`), and only import\nfrom `typing` for things with no built-in equivalent (e.g. `Callable`).\n",{"id":6161,"difficulty":84,"q":6162,"a":6163},"any-vs-object","What is the difference between `typing.Any` and `object`?","Both accept any value, but they are **opposites to a type checker**. `object`\nis the real **base of every class** — you can assign anything to it, but you\ncan only do `object`-level operations on it. `Any` is an **escape hatch**: it\nis compatible with **everything in both directions**, so the checker stops\nchecking — any attribute or call is allowed.\n\n```python\ndef f(x: object) -> None:\n    x.upper()        # type error: object has no 'upper'\n\ndef g(x: Any) -> None:\n    x.upper()        # OK — Any disables checking\n    x + 1            # also OK, no complaints\n```\n\nUse `object` when you genuinely accept anything but want to **keep type\nsafety** (forcing you to narrow with `isinstance` first). Use `Any` only to\ndeliberately **opt out** of checking. Rule of thumb: `Any` is contagious and\nhides bugs — prefer `object` or a precise type.\n",{"id":6165,"difficulty":63,"q":6166,"a":6167},"what-mypy-does","What does mypy do, and how is it different from Protocol-based typing?","**mypy** is a **static type checker**: it reads your annotations and flags\ntype mismatches **before you run the code** — no execution, no runtime cost.\nBy default it checks types **nominally** (by inheritance). `typing.Protocol`\nadds **structural typing** (a.k.a. duck typing): a class matches a Protocol\nif it has the right **methods\u002Fattributes**, even without inheriting from it.\n\n```python\nfrom typing import Protocol\n\nclass Closable(Protocol):\n    def close(self) -> None: ...\n\ndef shutdown(r: Closable) -> None:\n    r.close()\n\nclass File:                 # never imports\u002Finherits Closable\n    def close(self) -> None: ...\n\nshutdown(File())            # OK — File structurally matches\n```\n\nSo mypy verifies correctness, and `Protocol` lets it accept **anything with\nthe right shape** rather than a specific base class. Rule of thumb: use\nProtocols to type \"**anything that behaves like X**\" without forcing a\ncommon base class.\n",{"description":61},"Python interview questions on type hints, Optional and Union, generics with list vs List, typing.Any vs object, mypy, and Protocol structural typing.","python\u002Ftyping\u002Ftype-hints","Type Hints & Annotations","-Huf_PnQ17R6ZD2DTYZJptZVH8wQAKCHGmNxduo3rC4",{"id":6174,"title":6175,"body":6176,"description":61,"difficulty":63,"extension":64,"framework":21,"frameworkSlug":19,"meta":6180,"navigation":66,"order":22,"path":6181,"questions":6182,"related":207,"seo":6323,"seoDescription":6324,"stem":6325,"subtopic":6326,"topic":6327,"topicSlug":6328,"updated":1525,"__hash__":6329},"qa\u002Freact\u002Fhooks\u002Fuseeffect.md","Useeffect",{"type":58,"value":6177,"toc":6178},[],{"title":61,"searchDepth":22,"depth":22,"links":6179},[],{},"\u002Freact\u002Fhooks\u002Fuseeffect",[6183,6187,6191,6195,6199,6203,6207,6211,6215,6219,6223,6227,6231,6235,6239,6243,6247,6251,6255,6259,6263,6267,6271,6275,6279,6283,6287,6291,6295,6299,6303,6307,6311,6315,6319],{"id":6184,"difficulty":71,"q":6185,"a":6186},"what-is-useeffect","What does useEffect do?","`useEffect` lets you run **side effects** — work that reaches outside React's\nrender output: fetching data, setting up subscriptions or timers, manually\ntouching the DOM, logging. Render must stay pure (no side effects), so React\ngives you `useEffect` as the escape hatch that runs **after** the component has\nrendered and the screen is updated.\n\n```jsx\nuseEffect(() => {\n  document.title = `${count} unread`\n}, [count])\n```\n\nThe mental model isn't \"run this on mount\u002Fupdate\" but \"**keep this external\nthing in sync** with the state and props in my dependency array.\" React runs\nthe effect whenever one of those inputs changes so the outside world matches\nthe latest render.\n",{"id":6188,"difficulty":63,"q":6189,"a":6190},"deps-array","What does the dependency array control?","The dependency array tells React **when to re-run** the effect by comparing\neach item to its value from the previous render (using `Object.is`):\n\n- `[]` -> run **once** after the first render (no dependencies ever change).\n- `[a, b]` -> run after the first render, then again **only when `a` or `b`\n  change**.\n- **omitted** -> run after **every** render.\n\n```jsx\nuseEffect(() => {\n  const sub = source.subscribe(id)\n  return () => sub.unsubscribe()\n}, [id]) \u002F\u002F re-subscribe only when `id` changes\n```\n\nThe golden rule (enforced by the `react-hooks\u002Fexhaustive-deps` lint): every\nreactive value the effect *reads* — props, state, derived values — must be\nlisted. Omitting one to \"run less often\" is the #1 source of stale-data bugs.\n",{"id":6192,"difficulty":63,"q":6193,"a":6194},"cleanup","What is the cleanup function and when does it run?","If your effect sets something up that needs tearing down, **return a function**\nfrom it — that's the cleanup. React runs it in two situations: **before\nre-running** the effect (to undo the previous run) and when the component\n**unmounts**. This prevents leaked listeners, duplicate subscriptions, and\n\"setState on unmounted component\" warnings.\n\n```jsx\nuseEffect(() => {\n  const id = setInterval(tick, 1000)\n  return () => clearInterval(id) \u002F\u002F tear down before next run \u002F on unmount\n}, [])\n```\n\nThe sequence on a dependency change is: run cleanup for the *old* deps -> run\nthe effect for the *new* deps. So with `[id]`, changing `id` from `1` to `2`\nunsubscribes from `1` first, then subscribes to `2`. Forgetting cleanup is how\nyou end up with N intervals firing after N renders.\n",{"id":6196,"difficulty":71,"q":6197,"a":6198},"empty-deps","What happens with an empty dependency array?","An empty array `[]` means \"no reactive dependencies,\" so the effect runs\n**once** after the initial render and its cleanup runs **once** on unmount.\nIt's the closest hooks equivalent to the old `componentDidMount` +\n`componentWillUnmount` lifecycle pair.\n\n```jsx\nuseEffect(() => {\n  const onResize = () => setWidth(window.innerWidth)\n  window.addEventListener('resize', onResize)\n  return () => window.removeEventListener('resize', onResize)\n}, []) \u002F\u002F attach once, detach on unmount\n```\n\nCaveat for interviews: in React 18 **Strict Mode during development**, React\nintentionally mounts -> unmounts -> remounts components, so your `[]` effect and\nits cleanup fire twice. That's a deliberate check that your cleanup is correct;\nit does not happen in production.\n",{"id":6200,"difficulty":84,"q":6201,"a":6202},"stale-closure","What is a stale closure in useEffect?","An effect closes over the props and state from the render it was created in.\nIf you read a value but **leave it out of the dependency array**, the effect\nkeeps using the *frozen* value from that render and never sees updates — a\nstale closure.\n\n```jsx\n\u002F\u002F count is captured once (as 0) and never updated -> logs 0, 0, 0...\nuseEffect(() => {\n  const id = setInterval(() => console.log(count), 1000)\n  return () => clearInterval(id)\n}, []) \u002F\u002F missing `count`\n\n\u002F\u002F Option A: list the dependency (re-creates the interval each change)\n\u002F\u002F Option B: use a functional updater so you don't read `count` at all\nsetCount(c => c + 1)\n```\n\nFixes: include every value you read in the deps, use the functional updater\nform so the stale value never matters, or stash the latest value in a `useRef`\nwhen you deliberately want a long-lived effect that reads fresh data.\n",{"id":6204,"difficulty":84,"q":6205,"a":6206},"effect-timing","How does useEffect differ from useLayoutEffect?","Both run after render, but at different moments relative to the browser\n**paint**:\n\n- `useEffect` runs **asynchronously, after the browser has painted**. The user\n  sees the new frame, then the effect fires. Best for the vast majority of\n  effects (data, subscriptions) since it doesn't block visual updates.\n- `useLayoutEffect` runs **synchronously after DOM mutations but before\n  paint**. React blocks painting until it finishes, so you can measure layout\n  or mutate the DOM and the user never sees an intermediate state.\n\n```jsx\nuseLayoutEffect(() => {\n  const { height } = ref.current.getBoundingClientRect()\n  setTooltipTop(height) \u002F\u002F adjust position before the browser paints\n}, [])\n```\n\nUse `useLayoutEffect` only when you must read\u002Fwrite layout to avoid a visible\nflicker; because it's blocking, overusing it hurts performance. (On the server\nit doesn't run and warns — guard SSR code accordingly.)\n",{"id":6208,"difficulty":63,"q":6209,"a":6210},"data-fetching","How do you fetch data inside useEffect?","Start the request in the effect and store the result in state. List every value\nthe request depends on (like an `id`) in the dependency array so it refetches\nwhen they change.\n\n```jsx\nuseEffect(() => {\n  let active = true\n  fetch(`\u002Fapi\u002Fuser\u002F${id}`)\n    .then(r => r.json())\n    .then(data => { if (active) setUser(data) })\n  return () => { active = false } \u002F\u002F ignore a stale response\n}, [id])\n```\n\nThe `active` flag (or an `AbortController`) prevents a slow earlier request from\noverwriting a newer one. In real apps a data library usually handles this better.\n",{"id":6212,"difficulty":84,"q":6213,"a":6214},"fetch-race-condition","How do you avoid race conditions when fetching in an effect?","If `id` changes quickly, responses can arrive **out of order** and the older one\noverwrites the newer. Guard with a cleanup that invalidates the in-flight\nrequest — an ignore flag or an `AbortController`.\n\n```jsx\nuseEffect(() => {\n  const ctrl = new AbortController()\n  fetch(`\u002Fapi\u002F${id}`, { signal: ctrl.signal })\n    .then(r => r.json())\n    .then(setData)\n    .catch(e => { if (e.name !== 'AbortError') throw e })\n  return () => ctrl.abort() \u002F\u002F cancel the previous request\n}, [id])\n```\n\nReact runs the cleanup before the next effect, so the stale request is aborted\nand can't clobber fresh data.\n",{"id":6216,"difficulty":63,"q":6217,"a":6218},"fetch-vs-library","Why prefer a data library over fetching in useEffect?","Hand-rolled `useEffect` fetching means you reimplement caching, deduping,\nretries, race-condition handling, loading\u002Ferror states, and refetching — for\nevery call. Libraries like **React Query \u002F SWR \u002F RTK Query** give you all of that\ndeclaratively.\n\n```jsx\nconst { data, isLoading, error } = useQuery({\n  queryKey: ['user', id],\n  queryFn: () => fetchUser(id),\n})\n```\n\nThe React docs explicitly recommend a framework or data library for fetching.\nUse raw effect-fetching only for simple, one-off cases.\n",{"id":6220,"difficulty":84,"q":6221,"a":6222},"object-deps","Why does an object or array dependency re-run the effect every render?","Dependencies are compared by **reference** (`Object.is`). An object\u002Farray literal\ncreated during render is a **new reference each time**, so the effect sees a\n\"changed\" dependency on every render and re-runs endlessly.\n\n```jsx\n\u002F\u002F options is a new object every render -> effect runs every render\nconst options = { id }\nuseEffect(() => subscribe(options), [options])\n```\n\nFixes: depend on the **primitive** inside (`[id]`), build the object **inside**\nthe effect, or memoize it with `useMemo`. Same applies to functions passed as\ndeps — stabilize with `useCallback`.\n",{"id":6224,"difficulty":84,"q":6225,"a":6226},"usecallback-dep","How does useCallback help with effect dependencies?","A function defined in a component body is recreated each render (new reference).\nIf an effect depends on it, the effect re-runs every render. `useCallback`\nreturns a **stable** function identity that only changes when its own deps do.\n\n```jsx\nconst load = useCallback(() => fetchData(id), [id])\nuseEffect(() => { load() }, [load]) \u002F\u002F re-runs only when id changes\n```\n\nWithout it, the effect would fire on every render. `useCallback` is mainly about\n**referential stability** for deps and memoized children — not raw speed.\n",{"id":6228,"difficulty":63,"q":6229,"a":6230},"usememo-dep","How do you stabilize an object dependency with useMemo?","Wrap the object's creation in `useMemo` so it keeps the same reference until its\ninputs change, which keeps a dependent effect from re-running needlessly.\n\n```jsx\nconst filters = useMemo(() => ({ status, sort }), [status, sort])\nuseEffect(() => {\n  applyFilters(filters)\n}, [filters]) \u002F\u002F only when status or sort actually change\n```\n\nEquivalent alternative: skip the object and depend on `[status, sort]` directly.\nMemoize when the object must be passed around as a single value.\n",{"id":6232,"difficulty":63,"q":6233,"a":6234},"polling-interval","How do you poll an API on an interval with useEffect?","Set up the interval in the effect and **clear it in cleanup** so it doesn't leak\nor duplicate when deps change or the component unmounts.\n\n```jsx\nuseEffect(() => {\n  const id = setInterval(() => refetch(), 5000)\n  return () => clearInterval(id)\n}, [refetch])\n```\n\nIf `refetch` isn't stable, wrap it in `useCallback` or you'll tear down and\nrecreate the interval each render. For variable intervals, a `useRef`-based\n`useInterval` hook is a common pattern.\n",{"id":6236,"difficulty":84,"q":6237,"a":6238},"debounce-effect","How do you debounce a value with useEffect?","Start a timer in the effect that updates a \"debounced\" state, and **clear the\ntimer in cleanup** — so rapid changes keep resetting the timer until input\nsettles.\n\n```jsx\nconst [query, setQuery] = useState('')\nconst [debounced, setDebounced] = useState(query)\nuseEffect(() => {\n  const id = setTimeout(() => setDebounced(query), 300)\n  return () => clearTimeout(id) \u002F\u002F cancel if query changes again\n}, [query])\n\u002F\u002F run search on `debounced`, not `query`\n```\n\nEach keystroke re-runs the effect, whose cleanup cancels the previous pending\ntimer — so the update only fires after 300ms of quiet.\n",{"id":6240,"difficulty":84,"q":6241,"a":6242},"subscribe-external","How do you subscribe to an external store from an effect?","Subscribe in the effect and **unsubscribe in cleanup**. For external stores,\nReact 18's `useSyncExternalStore` is the purpose-built hook (tear-free with\nconcurrent rendering), but a manual effect works for simple cases.\n\n```jsx\nuseEffect(() => {\n  const unsub = store.subscribe(() => setValue(store.get()))\n  setValue(store.get())   \u002F\u002F sync the initial value\n  return unsub            \u002F\u002F cleanup unsubscribes\n}, [store])\n```\n\nAlways read the current value once on subscribe so you don't miss a change that\nhappened between render and effect. Prefer `useSyncExternalStore` for shared\nstores.\n",{"id":6244,"difficulty":63,"q":6245,"a":6246},"localstorage-sync","How do you sync state to localStorage with useEffect?","Write to `localStorage` in an effect that depends on the value, and read it lazily\nin the initializer so it's only parsed once.\n\n```jsx\nconst [theme, setTheme] = useState(() => localStorage.getItem('theme') ?? 'light')\nuseEffect(() => {\n  localStorage.setItem('theme', theme)\n}, [theme])\n```\n\nThe lazy initializer avoids reading storage on every render; the effect persists\nchanges. Guard `localStorage` access for SSR (it doesn't exist on the server) —\neffects don't run server-side, so this pattern is SSR-safe.\n",{"id":6248,"difficulty":84,"q":6249,"a":6250},"not-need-effect","When do you NOT need a useEffect?","Effects are for **synchronizing with external systems**, not for reacting to user\nevents or computing values. If something happens **because the user did\nsomething**, do it in the **event handler**, not an effect.\n\n```jsx\n\u002F\u002F effect reacting to a click that already happened\nuseEffect(() => { if (submitted) postData() }, [submitted])\n\u002F\u002F just do it in the handler\nfunction onSubmit() { postData() }\n```\n\n\"You Might Not Need an Effect\" (React docs): skip effects for derived data,\nevent responses, and resetting state on prop change (use `key` instead).\n",{"id":6252,"difficulty":63,"q":6253,"a":6254},"derive-not-effect","Why shouldn't you use an effect to compute derived state?","Storing computed data in state and syncing it with an effect causes an **extra\nrender** and risks the copy going stale. Just compute it during render.\n\n```jsx\n\u002F\u002F effect + extra state + extra render\nconst [full, setFull] = useState('')\nuseEffect(() => setFull(`${first} ${last}`), [first, last])\n\n\u002F\u002F derive in render (memoize only if expensive)\nconst full = `${first} ${last}`\n```\n\nAn effect-to-set-state for something derivable is a classic anti-pattern flagged\nin the React docs.\n",{"id":6256,"difficulty":84,"q":6257,"a":6258},"lint-suppress-danger","Why is disabling the exhaustive-deps lint dangerous?","Adding `\u002F\u002F eslint-disable-next-line react-hooks\u002Fexhaustive-deps` to silence a\nmissing dependency doesn't fix the bug — it hides it. The effect keeps using\n**stale** captured values and silently breaks when those values change.\n\n```jsx\n\u002F\u002F suppressing the warning to \"run once\" -> stale `userId`\nuseEffect(() => { fetchData(userId) }, []) \u002F\u002F eslint-disable-line\n```\n\nInstead, fix the root cause: include the dep, move logic inside the effect, use a\nfunctional setter, or stabilize the value with `useCallback`\u002F`useRef`. Suppress\nonly when you fully understand why it's safe.\n",{"id":6260,"difficulty":63,"q":6261,"a":6262},"cleanup-order2","In what order do cleanup and the next effect run?","On a dependency change, React runs the **previous** effect's cleanup **first**,\nthen runs the **new** effect. It never overlaps them.\n\n```jsx\nuseEffect(() => {\n  console.log('subscribe', id)\n  return () => console.log('unsubscribe', id)\n}, [id])\n\u002F\u002F id: 1 -> 2 logs: \"unsubscribe 1\" then \"subscribe 2\"\n```\n\nThis ordering guarantees you tear down the old subscription before setting up the\nnew one — no leaks, no duplicates. On unmount, only the last cleanup runs.\n",{"id":6264,"difficulty":84,"q":6265,"a":6266},"strict-double","Why does my effect run twice in development?","In React 18 **Strict Mode** (development only), React mounts each component,\n**unmounts it, and remounts it** to surface effects that aren't cleanup-safe. So\na mount effect + its cleanup fire twice.\n\n```jsx\nuseEffect(() => {\n  console.log('run')        \u002F\u002F logs twice in dev Strict Mode\n  return () => console.log('cleanup')\n}, [])\n```\n\nIt does **not** happen in production. If double-invocation breaks something\n(e.g. duplicate requests), that's a sign your effect needs proper cleanup or\nshouldn't be an effect at all — Strict Mode is doing its job.\n",{"id":6268,"difficulty":63,"q":6269,"a":6270},"infinite-effect-loop","What causes an infinite loop in useEffect?","Setting state in an effect whose dependency **changes as a result of that state**\n— or using an unstable object\u002Farray\u002Ffunction dependency created each render.\n\n```jsx\n\u002F\u002F sets data -> re-render -> new [] dep -> runs again -> loop\nuseEffect(() => setData(compute()), [{}])\n\n\u002F\u002F depends on the state it updates\nuseEffect(() => setCount(count + 1), [count])\n```\n\nFixes: stabilize deps (memoize objects\u002Ffunctions), depend on primitives, or use\na functional updater so the effect needn't depend on the state it sets.\n",{"id":6272,"difficulty":63,"q":6273,"a":6274},"async-effect-directly","Why can't the useEffect callback be async?","An `async` function returns a **Promise**, but React expects the effect callback\nto return **either nothing or a cleanup function**. Returning a Promise breaks\ncleanup. Define an async function **inside** and call it.\n\n```jsx\n\u002F\u002F async effect returns a Promise, not a cleanup fn\nuseEffect(async () => { await load() }, [])\n\n\u002F\u002F inner async function\nuseEffect(() => {\n  (async () => { await load() })()\n}, [])\n```\n\nThis keeps the return value available for cleanup while still letting you use\n`await` inside.\n",{"id":6276,"difficulty":71,"q":6277,"a":6278},"event-listener-effect","How do you add and remove a global event listener?","Add the listener in the effect and remove **the same function reference** in\ncleanup, so it's detached on unmount and not duplicated on re-runs.\n\n```jsx\nuseEffect(() => {\n  const onKey = e => { if (e.key === 'Escape') close() }\n  window.addEventListener('keydown', onKey)\n  return () => window.removeEventListener('keydown', onKey)\n}, [close])\n```\n\nThe cleanup must reference the **exact** function passed to `addEventListener`\n(an inline arrow in both calls won't match), which is why it's defined once\ninside the effect.\n",{"id":6280,"difficulty":63,"q":6281,"a":6282},"multiple-effects","Should you split logic into multiple effects?","Yes — use **separate effects for unrelated concerns**, each with its own\ndependency array. One effect per responsibility is clearer and avoids re-running\nunrelated logic when only one dependency changes.\n\n```jsx\nuseEffect(() => { document.title = title }, [title])     \u002F\u002F title sync\nuseEffect(() => {\n  const id = connect(roomId)\n  return () => disconnect(id)\n}, [roomId])                                             \u002F\u002F connection\n```\n\nDon't cram title updates and a subscription into one effect just because they're\nin the same component — split by what they synchronize.\n",{"id":6284,"difficulty":63,"q":6285,"a":6286},"effect-run-timing","When exactly does useEffect run relative to rendering?","The sequence is: React renders (calls your component) -> commits changes to the\nDOM -> **browser paints** -> *then* `useEffect` runs asynchronously. So effects\nnever block the visual update.\n\n```\nrender -> commit (DOM updated) -> paint -> useEffect\n```\n\nThis is why you shouldn't read final layout measurements that must be applied\n*before* paint in `useEffect` — use `useLayoutEffect` for those. For most work\n(fetching, subscriptions, logging), running after paint is exactly what you want.\n",{"id":6288,"difficulty":84,"q":6289,"a":6290},"ref-latest-in-effect","How do you read the latest prop\u002Fstate in a long-lived effect without re-subscribing?","Mirror the value in a `useRef` updated each render, and read `ref.current` inside\nthe effect. The effect can keep an empty dep array (set up once) yet always see\nfresh data.\n\n```jsx\nconst cbRef = useRef(onTick)\nuseEffect(() => { cbRef.current = onTick }) \u002F\u002F keep it current\nuseEffect(() => {\n  const id = setInterval(() => cbRef.current(), 1000)\n  return () => clearInterval(id)\n}, []) \u002F\u002F interval created once, always calls the latest onTick\n```\n\nThis is the core of the `useInterval`\u002F`useEventCallback` patterns — avoid stale\nclosures without tearing down the subscription on every change.\n",{"id":6292,"difficulty":71,"q":6293,"a":6294},"effect-once-mount","How do you run an effect only once when the component mounts?","Pass an **empty dependency array**. The effect runs after the first render and\nnever again (its cleanup runs on unmount).\n\n```jsx\nuseEffect(() => {\n  analytics.pageView()\n}, []) \u002F\u002F mount only\n```\n\nCaveat: in dev Strict Mode it runs twice, and the lint rule will warn if the\neffect actually *uses* props\u002Fstate you left out — so \"run once\" should genuinely\nhave no reactive dependencies.\n",{"id":6296,"difficulty":63,"q":6297,"a":6298},"dep-primitive-vs-object","Why are primitive dependencies safer than object dependencies?","Primitives (`string`, `number`, `boolean`) compare by **value**, so equal values\nare \"unchanged\" and the effect doesn't re-run. Objects\u002Farrays\u002Ffunctions compare\nby **reference**, so a freshly created one looks changed every render.\n\n```jsx\nuseEffect(() => {}, [userId])        \u002F\u002F re-runs only when the number changes\nuseEffect(() => {}, [{ userId }])    \u002F\u002F new object each render -> always re-runs\n```\n\nPrefer depending on the **specific primitive fields** you read rather than a\nwhole object — it's both safer and more precise.\n",{"id":6300,"difficulty":63,"q":6301,"a":6302},"server-no-run","Do effects run during server-side rendering?","No. `useEffect` (and `useLayoutEffect`) **do not run on the server** — they only\nrun in the browser after hydration. So effects are the right place for\nbrowser-only APIs (`window`, `localStorage`, `IntersectionObserver`).\n\n```jsx\nuseEffect(() => {\n  const mq = window.matchMedia('(min-width: 768px)') \u002F\u002F browser-only, safe here\n  \u002F\u002F ...\n}, [])\n```\n\nDon't access `window`\u002F`document` during render (it crashes SSR); defer it to an\neffect. `useLayoutEffect` additionally **warns** during SSR — guard or use\n`useEffect` there.\n",{"id":6304,"difficulty":84,"q":6305,"a":6306},"reset-on-prop-change","How do you reset state when a prop changes, without an effect?","Avoid the effect-that-resets-state pattern. Prefer **changing the `key`** to\nremount the subtree, or the conditional set-during-render pattern for partial\nresets.\n\n```jsx\n\u002F\u002F remount on userId change -> all state resets\n\u003CProfile key={userId} userId={userId} \u002F>\n\n\u002F\u002F partial reset during render (no effect, no extra paint)\nconst [prevId, setPrevId] = useState(id)\nif (id !== prevId) { setPrevId(id); setComment('') }\n```\n\nUsing an effect to watch the prop and call setters causes an extra render and is\nflagged as an anti-pattern in the docs.\n",{"id":6308,"difficulty":63,"q":6309,"a":6310},"cleanup-async-fetch","How does the ignore-flag pattern prevent setting state after unmount?","A boolean captured in the effect, flipped in cleanup, lets the async callback\ncheck whether the component is still mounted (and the request still current)\nbefore calling a setter.\n\n```jsx\nuseEffect(() => {\n  let ignore = false\n  load(id).then(data => { if (!ignore) setData(data) })\n  return () => { ignore = true } \u002F\u002F later resolution is ignored\n}, [id])\n```\n\nThis both prevents the \"can't update an unmounted component\" warning and avoids a\nstale earlier request overwriting newer data.\n",{"id":6312,"difficulty":84,"q":6313,"a":6314},"chained-effects-antipattern","Why are chains of effects that trigger each other an anti-pattern?","An effect that sets state, which triggers another effect that sets more state,\ncreates cascading renders that are hard to follow and inefficient — each step is\na separate render pass.\n\n```jsx\n\u002F\u002F effect -> setState -> effect -> setState ...\nuseEffect(() => setB(a + 1), [a])\nuseEffect(() => setC(b * 2), [b])\n```\n\nPrefer computing the values **together during render** (derive `b` and `c` from\n`a`), or do the multi-step update in a single **event handler**. Reserve effects\nfor genuine external synchronization, not internal state cascades.\n",{"id":6316,"difficulty":63,"q":6317,"a":6318},"effect-vs-render-purity","Why must side effects live in useEffect and not in the render body?","Rendering must be **pure** — given the same props\u002Fstate it returns the same JSX\nwith no side effects. React may call your component multiple times, bail out, or\ndiscard renders (concurrent features), so a side effect in render could run\nunexpectedly, repeatedly, or never.\n\n```jsx\n\u002F\u002F side effect during render — runs on every render, breaks purity\ndocument.title = title\n\u002F\u002F after commit, controlled by deps\nuseEffect(() => { document.title = title }, [title])\n```\n\nKeeping effects out of render is what lets React safely re-render and optimize.\n",{"id":6320,"difficulty":71,"q":6321,"a":6322},"analytics-on-change","How do you run code after a specific value changes?","Use an effect that **depends on that value** — it runs after each commit where\nthe value changed.\n\n```jsx\nuseEffect(() => {\n  analytics.track('step_changed', { step })\n}, [step])\n```\n\nThis is the hooks replacement for the class `setState` callback or\n`componentDidUpdate` comparisons: react to the new value in an effect keyed on\nit. Make sure the dependency is the exact value you're reacting to.\n",{"description":61},"React useEffect interview questions and answers — the dependency array, cleanup functions, effect timing and common mistakes.","react\u002Fhooks\u002Fuseeffect","useEffect","Hooks","hooks","WadYDpcEpirDvJ9N1brliOprDPb6eXUhfXGkfT5T7go",{"id":6331,"title":6332,"body":6333,"description":61,"difficulty":71,"extension":64,"framework":21,"frameworkSlug":19,"meta":6337,"navigation":66,"order":12,"path":6338,"questions":6339,"related":207,"seo":6476,"seoDescription":6477,"stem":6478,"subtopic":6479,"topic":6327,"topicSlug":6328,"updated":1525,"__hash__":6480},"qa\u002Freact\u002Fhooks\u002Fusestate.md","Usestate",{"type":58,"value":6334,"toc":6335},[],{"title":61,"searchDepth":22,"depth":22,"links":6336},[],{},"\u002Freact\u002Fhooks\u002Fusestate",[6340,6344,6348,6352,6356,6360,6364,6368,6372,6376,6380,6384,6388,6392,6396,6400,6404,6408,6412,6416,6420,6424,6428,6432,6436,6440,6444,6448,6452,6456,6460,6464,6468,6472],{"id":6341,"difficulty":71,"q":6342,"a":6343},"what-is-usestate","What does useState return?","`useState` returns an array of exactly two elements: the **current state\nvalue** for this render, and a **setter function** that schedules an update\nand triggers a re-render. You destructure them, and the `[value, setValue]`\nnaming convention is just that — a convention, not something React enforces.\n\n```jsx\nconst [count, setCount] = useState(0)\n\u002F\u002F     ▲ current value  ▲ setter that re-renders with the next value\n```\n\nA few things that trip people up in interviews:\n\n- The argument (`0` here) is only the **initial** value. On every render\n  after the first, React ignores it and hands you the latest stored value.\n- The setter has a **stable identity** — React guarantees it never changes\n  between renders, so it's safe to omit from `useEffect`\u002F`useCallback`\n  dependency arrays.\n- Calling the setter does **not** mutate `count` in the current scope; it\n  asks React to render again with a new value.\n",{"id":6345,"difficulty":63,"q":6346,"a":6347},"async-state","Why does state appear to be \"one render behind\"?","Because `count` is a **const captured by this render's closure**, not a live\nreference to a mutable box. Each render gets its own `count` constant frozen\nat the value it had when that render ran. Calling `setCount` schedules a\n*future* render with a new value — it cannot reach back and change the\n`count` you're currently looking at.\n\n```jsx\nfunction handleClick() {\n  console.log(count)   \u002F\u002F e.g. 0\n  setCount(count + 1)  \u002F\u002F schedules a render where count will be 1\n  console.log(count)   \u002F\u002F STILL 0 — same render, same frozen constant\n}\n```\n\nSo state isn't really \"behind\" — you're reading a snapshot. The new value\nbecomes visible only in the next render's function body. If you need the\nupdated value immediately after setting it, derive it locally\n(`const next = count + 1`) or read it in an effect that runs after the\nre-render.\n",{"id":6349,"difficulty":63,"q":6350,"a":6351},"functional-update","When should you use a functional state update?","Use the functional form — `setCount(c => c + 1)` — whenever the next state is\n**derived from the previous state**, especially when several updates happen in\none event or across async boundaries. React passes the most up-to-date value\ninto your updater, so you never base a calculation on a stale snapshot.\n\n```jsx\n\u002F\u002F All three read the same stale `count`, so this adds 1, not 3\nsetCount(count + 1)\nsetCount(count + 1)\nsetCount(count + 1)\n\n\u002F\u002F Each updater receives the result of the previous one -> +3\nsetCount(c => c + 1)\nsetCount(c => c + 1)\nsetCount(c => c + 1)\n```\n\nRule of thumb: if the new value mentions the old value, prefer the function\nform. If you're setting an unrelated value (`setCount(0)`), the direct form\nis fine.\n",{"id":6353,"difficulty":63,"q":6354,"a":6355},"lazy-init","What is lazy initial state?","If your initial value is expensive to compute, pass a **function** to\n`useState` instead of the value itself. React calls that function **only on\nthe first render** and ignores it afterwards. Passing the value directly would\nre-run the expensive computation on *every* render and then throw the result\naway.\n\n```jsx\n\u002F\u002F readFromLocalStorage() runs on every single render\nconst [items, setItems] = useState(readFromLocalStorage())\n\n\u002F\u002F runs once, on mount only\nconst [items, setItems] = useState(() => readFromLocalStorage())\n```\n\nWatch the distinction: `useState(expensive())` *calls* `expensive` every\nrender (its return value is the argument), whereas `useState(expensive)` \u002F\n`useState(() => expensive())` hands React the function to call once.\n",{"id":6357,"difficulty":63,"q":6358,"a":6359},"object-state","How do you update an object in state?","Unlike `this.setState` in class components, the `useState` setter **replaces**\nthe value — it does not shallow-merge. To change one field of an object you\nmust spread the previous object yourself and override the field, returning a\n**new** object (mutating the existing one won't trigger a re-render because the\nreference is unchanged).\n\n```jsx\nconst [user, setUser] = useState({ name: 'Ada', age: 36 })\n\n\u002F\u002F new object, old fields preserved, name overridden\nsetUser(u => ({ ...u, name: 'Grace' }))\n\n\u002F\u002F mutates in place — same reference, React skips the re-render\nuser.name = 'Grace'\nsetUser(user)\n```\n\nFor deeply nested state this spreading gets verbose; that's often the signal\nto reach for `useReducer` or a state library.\n",{"id":6361,"difficulty":84,"q":6362,"a":6363},"batching","What is state batching?","Batching is React grouping multiple state updates into a **single re-render**\nfor performance, instead of re-rendering once per `setState` call. If you call\nthree setters in one click handler, React processes them together and renders\nonce.\n\n```jsx\nfunction handleClick() {\n  setA(1)\n  setB(2)\n  setC(3)\n  \u002F\u002F ONE re-render, not three\n}\n```\n\nBefore React 18, batching only happened inside React event handlers; updates\nin `setTimeout`, promises, or native event listeners each caused their own\nrender. **React 18's automatic batching** extends grouping to those async\ncontexts too. If you ever need to opt out and force a synchronous, separate\nrender, wrap the update in `flushSync` from `react-dom`.\n",{"id":6365,"difficulty":63,"q":6366,"a":6367},"derived-state","Should you store computed\u002Fderived values in state?","Usually **no**. If a value can be calculated from existing props or state,\nderive it **during render** instead of duplicating it in `useState` — extra\nstate can drift out of sync and forces you to keep two things updated.\n\n```jsx\n\u002F\u002F redundant state that can desync\nconst [items, setItems] = useState([])\nconst [count, setCount] = useState(0)\n\n\u002F\u002F derive it\nconst [items, setItems] = useState([])\nconst count = items.length\n```\n\nOnly store something in state if it's genuinely independent input. \"You might\nnot need state\" is the React team's own guidance.\n",{"id":6369,"difficulty":63,"q":6370,"a":6371},"lift-state-up","What does \"lifting state up\" mean?","When two components need to share or stay in sync over the same data, you move\nthe state to their **closest common parent** and pass it down as props plus a\nsetter callback. The parent becomes the single source of truth.\n\n```jsx\nfunction Parent() {\n  const [value, setValue] = useState('')\n  return (\n    \u003C>\n      \u003CInput value={value} onChange={setValue} \u002F>\n      \u003CPreview value={value} \u002F>\n    \u003C\u002F>\n  )\n}\n```\n\nIt's the standard fix for \"these siblings need the same data.\" When lifting gets\npainful across many levels, that's the signal to reach for Context or a store.\n",{"id":6373,"difficulty":63,"q":6374,"a":6375},"usestate-vs-useref","When should you use useRef instead of useState?","Use `useState` for values that should **trigger a re-render** when they change.\nUse `useRef` for mutable values that should **persist across renders but NOT\ncause re-renders** — timer ids, previous values, DOM nodes.\n\n```jsx\nconst [count, setCount] = useState(0) \u002F\u002F UI depends on it -> re-render\nconst renders = useRef(0)             \u002F\u002F bookkeeping -> no re-render\nrenders.current++\n```\n\nChanging `ref.current` is invisible to React's render cycle. If the screen needs\nto reflect the value, it belongs in state; otherwise a ref avoids needless\nrenders.\n",{"id":6377,"difficulty":84,"q":6378,"a":6379},"reset-state-key","How do you reset a component's state to its initial values?","The cleanest way is to change the component's **`key`**. React treats a new key\nas a brand-new component, unmounting the old instance (discarding its state) and\nmounting a fresh one — no manual reset code.\n\n```jsx\n\u003CProfile key={userId} userId={userId} \u002F>\n\u002F\u002F when userId changes, Profile remounts with fresh state\n```\n\nAlternatives are manually calling setters back to initial values, but `key` is\nidiomatic for \"start this subtree over.\" Avoid resetting state inside an effect\nby watching a prop — the `key` approach is simpler and bug-free.\n",{"id":6381,"difficulty":84,"q":6382,"a":6383},"store-function-state","How do you store a function in state?","Because the `useState` setter treats a **function argument as an updater**, you\nmust wrap a function you want to *store* in another function — otherwise React\ncalls it instead of saving it.\n\n```jsx\n\u002F\u002F React invokes handleClick to compute the next state\nconst [fn, setFn] = useState(handleClick)\nsetFn(handleClick)\n\n\u002F\u002F wrap it so it's stored, not called\nconst [fn, setFn] = useState(() => handleClick)\nsetFn(() => handleClick)\n```\n\nThe same rule applies to lazy initialization. Storing functions in state is rare\n— usually a ref or just defining the function in render is cleaner.\n",{"id":6385,"difficulty":71,"q":6386,"a":6387},"array-state-add","How do you add and remove items in array state?","Treat the array as **immutable** — never `push`\u002F`splice` the existing array\n(same reference -> no re-render). Build a new array with spread or `filter`.\n\n```jsx\n\u002F\u002F add\nsetItems(prev => [...prev, newItem])\n\u002F\u002F remove by id\nsetItems(prev => prev.filter(it => it.id !== id))\n\u002F\u002F insert at index\nsetItems(prev => [...prev.slice(0, i), newItem, ...prev.slice(i)])\n```\n\nUsing the functional updater (`prev =>`) keeps you correct when several updates\nbatch together.\n",{"id":6389,"difficulty":63,"q":6390,"a":6391},"array-state-update","How do you update one object inside an array in state?","Map over the array, returning a **new object** for the matching item and the\noriginals for the rest. Mutating the found object in place won't re-render and\ncan corrupt previous renders.\n\n```jsx\nsetUsers(prev =>\n  prev.map(u => u.id === id ? { ...u, name: 'Ada' } : u)\n)\n```\n\nThe rule: new array **and** new object for whatever you change. For deeply\nnested updates this gets verbose — a signal to use `useReducer` or Immer.\n",{"id":6393,"difficulty":84,"q":6394,"a":6395},"usestate-vs-usereducer","When should you choose useReducer over useState?","Reach for `useReducer` when state is **complex** (multiple sub-values that change\ntogether), when the **next state depends on intricate logic**, or when you want\nto **centralize update logic** in one tested function instead of scattering\nsetters.\n\n```jsx\nconst [state, dispatch] = useReducer(reducer, initial)\ndispatch({ type: 'increment', by: 2 })\n```\n\n`useState` is best for simple, independent values. A heuristic: if you find\nyourself calling several setters together or your setter logic is branchy, a\nreducer makes intent clearer and easier to test.\n",{"id":6397,"difficulty":71,"q":6398,"a":6399},"controlled-input","How do you build a controlled input with useState?","A controlled input gets its `value` from state and updates state on every\nkeystroke via `onChange`, making React the single source of truth.\n\n```jsx\nconst [text, setText] = useState('')\n\u003Cinput value={text} onChange={e => setText(e.target.value)} \u002F>\n```\n\nForgetting `onChange` while setting `value` makes the field **read-only** (React\nwarns). The benefit is you can validate, format, or react to every change; the\ncost is a re-render per keystroke (rarely a problem).\n",{"id":6401,"difficulty":63,"q":6402,"a":6403},"controlled-vs-uncontrolled","What is the difference between controlled and uncontrolled components?","- **Controlled** — React state holds the value (`value` + `onChange`). Predictable\n  and easy to validate, but re-renders on each change.\n- **Uncontrolled** — the DOM holds the value; you read it via a `ref` when needed\n  (`defaultValue` for the initial value).\n\n```jsx\n\u002F\u002F uncontrolled\nconst ref = useRef()\n\u003Cinput defaultValue=\"hi\" ref={ref} \u002F>\n\u002F\u002F read ref.current.value on submit\n```\n\nControlled is the default recommendation; uncontrolled suits simple forms,\nfile inputs, or integrating non-React widgets.\n",{"id":6405,"difficulty":63,"q":6406,"a":6407},"multiple-vs-single-object","Should you use multiple state variables or one state object?","Prefer **multiple `useState` calls** for values that change independently — it's\nsimpler and you don't have to spread-merge on every update. Group into one object\nonly when fields genuinely change **together**.\n\n```jsx\n\u002F\u002F independent values\nconst [name, setName] = useState('')\nconst [age, setAge] = useState(0)\n\n\u002F\u002F grouping requires manual merge (no auto-merge like class setState)\nsetForm(prev => ({ ...prev, name: 'Ada' }))\n```\n\nRemember the `useState` setter **replaces**, it doesn't merge — so an object of\nstate means spreading the rest every time.\n",{"id":6409,"difficulty":84,"q":6410,"a":6411},"nested-object-update","How do you update deeply nested state immutably?","Spread at **every** level you change, all the way down — only the touched\nbranches get new references.\n\n```jsx\nsetUser(prev => ({\n  ...prev,\n  address: { ...prev.address, city: 'Paris' },\n}))\n```\n\nThis is error-prone and verbose for deep trees. Options: restructure to flatter\nstate, switch to `useReducer`, or use **Immer** (`produce`) which lets you\n\"mutate\" a draft and produces the immutable update for you.\n",{"id":6413,"difficulty":63,"q":6414,"a":6415},"avoid-redundant-state","What is redundant state and why avoid it?","Redundant state is data you keep in `useState` that's already derivable from\nother state or props. It invites bugs because you must remember to update it\neverywhere, and the copies can disagree.\n\n```jsx\n\u002F\u002F fullName must be kept in sync manually\nconst [fullName, setFullName] = useState('')\n\u002F\u002F derive it\nconst fullName = `${first} ${last}`\n```\n\nKeep state **minimal and orthogonal** — the smallest set of independent values\nfrom which everything else is computed during render.\n",{"id":6417,"difficulty":71,"q":6418,"a":6419},"toggle-boolean","How do you toggle a boolean in state?","Use the functional updater so you always flip the **latest** value, which matters\nif toggles can batch.\n\n```jsx\nconst [open, setOpen] = useState(false)\nconst toggle = () => setOpen(o => !o)\n```\n\nAvoid `setOpen(!open)` in code paths that may run multiple times in one event —\nit reads a possibly stale `open`. The functional form is always safe.\n",{"id":6421,"difficulty":84,"q":6422,"a":6423},"prev-in-async","How do you read the latest state inside an async callback?","A callback captures the state value from the render it was created in, so after\nan `await` it may be **stale**. To act on the latest value, use the functional\nupdater (which receives the current value) or store it in a ref.\n\n```jsx\nasync function save() {\n  await delay(1000)\n  \u002F\u002F `count` is whatever it was when save() was created\n  \u002F\u002F read the latest via the updater\n  setCount(latest => { send(latest); return latest })\n}\n```\n\nCleaner still: pass the needed value as an argument, or keep a `useRef` mirror of\nthe state for \"read latest\" access without triggering renders.\n",{"id":6425,"difficulty":84,"q":6426,"a":6427},"set-bailout","Does setting state to the same value cause a re-render?","If you set state to a value that's **`Object.is`-equal** to the current one,\nReact **bails out** and skips re-rendering that component (it may still re-run\nthe component once to check, then stop).\n\n```jsx\nconst [n, setN] = useState(0)\nsetN(0) \u002F\u002F same value -> React bails out, no committed re-render\n```\n\nThe catch: this is **reference** equality. `setItems([])` with a *new* empty\narray is a different reference, so it **does** re-render even though the contents\nlook identical. Don't create fresh objects\u002Farrays for \"no change.\"\n",{"id":6429,"difficulty":71,"q":6430,"a":6431},"state-vs-props","What is the difference between state and props?","- **State** is data a component **owns and can change** over time via its setter.\n- **Props** are data **passed in from a parent**; the child treats them as\n  **read-only**.\n\n```jsx\nfunction Counter({ step }) {        \u002F\u002F step is a prop (read-only)\n  const [count, setCount] = useState(0) \u002F\u002F count is state (owned)\n  return \u003Cbutton onClick={() => setCount(c => c + step)}>{count}\u003C\u002Fbutton>\n}\n```\n\nA child never mutates props; to change parent data it calls a callback prop. One\ncomponent's state is often another's props (passed down).\n",{"id":6433,"difficulty":63,"q":6434,"a":6435},"rules-of-hooks","Why must useState be called at the top level, not in conditions?","React identifies each hook by its **call order**, not a name. Calling `useState`\ninside a condition, loop, or after an early return changes that order between\nrenders, so React mismatches state to the wrong hook.\n\n```jsx\n\u002F\u002F breaks hook ordering\nif (loggedIn) {\n  const [name, setName] = useState('')\n}\n\u002F\u002F always call unconditionally; branch on the value\nconst [name, setName] = useState('')\nif (loggedIn) { \u002F* use name *\u002F }\n```\n\nAlways call hooks at the top level of the component, in the same order every\nrender — the `eslint-plugin-react-hooks` rule enforces this.\n",{"id":6437,"difficulty":63,"q":6438,"a":6439},"state-no-rerender","When does updating state not trigger a re-render?","Two common cases: (1) you **mutated** the existing object\u002Farray and passed the\nsame reference, so React sees no change; or (2) you set a primitive to the\n**same value** (React bails out via `Object.is`).\n\n```jsx\n\u002F\u002F mutate + same reference -> no re-render\nuser.name = 'Ada'\nsetUser(user)\n\u002F\u002F new reference\nsetUser({ ...user, name: 'Ada' })\n```\n\nThe fix is always to produce a **new reference** for changed objects\u002Farrays. If\nthe UI \"isn't updating,\" this mutation trap is the first thing to check.\n",{"id":6441,"difficulty":84,"q":6442,"a":6443},"set-during-render","Can you call a state setter during render?","Generally you should not — setting state in the render body unconditionally\ncauses an **infinite loop**. React *does* support a narrow pattern: calling a\nsetter **conditionally during render** to adjust state based on a prop change,\nwhich it handles without an extra paint.\n\n```jsx\n\u002F\u002F rare, allowed: derive on prop change without an effect\nconst [prevId, setPrevId] = useState(id)\nif (id !== prevId) {\n  setPrevId(id)\n  setSelection(null) \u002F\u002F reset when id changes, no effect needed\n}\n```\n\nMost of the time you don't need this — prefer deriving values or the `key` reset\ntrick. Never call a setter unconditionally in render.\n",{"id":6445,"difficulty":63,"q":6446,"a":6447},"setstate-loop","What causes an infinite re-render loop with useState?","Calling a setter **unconditionally during render**, or inside an effect whose\ndependencies you keep changing, makes React render -> set -> render forever.\n\n```jsx\n\u002F\u002F sets state every render -> infinite loop\nconst [n, setN] = useState(0)\nsetN(n + 1)\n\n\u002F\u002F effect with a new object dep each render\nuseEffect(() => setData(load()), [{}])\n```\n\nFixes: only set state in **event handlers** or **effects with stable deps**,\nderive values instead of storing them, and avoid fresh object\u002Farray literals in\ndependency arrays.\n",{"id":6449,"difficulty":84,"q":6450,"a":6451},"state-from-props","Why doesn't state update when the prop used to initialize it changes?","The `useState` initializer is only read on the **first render**. Passing a prop\nas the initial value captures it once; later changes to the prop don't flow into\nthe state.\n\n```jsx\nfunction Field({ initial }) {\n  const [value, setValue] = useState(initial) \u002F\u002F only the first `initial` is used\n  \u002F\u002F later `initial` changes are ignored\n}\n```\n\nIf you truly need to reset when the prop changes, use the **`key`** prop to\nremount, or the conditional set-during-render pattern. Often the better answer is\nto not copy the prop into state at all.\n",{"id":6453,"difficulty":63,"q":6454,"a":6455},"expensive-derived","How do you cache an expensive derived value without storing it in state?","Use `useMemo` — it recomputes the value only when its dependencies change, so you\nget the benefit of a cached derivation **without** the desync risk of putting it\nin state.\n\n```jsx\nconst sorted = useMemo(\n  () => [...items].sort(compare),\n  [items]\n)\n```\n\nThis keeps `items` as the single source of truth while avoiding re-sorting on\nevery keystroke. Don't reach for `useMemo` until the computation is actually\nexpensive — needless memoization adds its own overhead.\n",{"id":6457,"difficulty":63,"q":6458,"a":6459},"state-colocation","Where should state live in a React component tree?","Keep state as **close as possible** to where it's used (colocation), and lift it\nonly as high as the nearest common ancestor that needs to share it. Over-lifting\nstate to the top causes unnecessary re-renders and prop drilling.\n\n```jsx\n\u002F\u002F a modal's \"open\" state belongs in the component that owns the modal,\n\u002F\u002F not in the app root\nfunction Toolbar() {\n  const [open, setOpen] = useState(false)\n  \u002F\u002F ...\n}\n```\n\nColocated state means fewer renders and simpler components; global\u002Fapp state\nshould be reserved for genuinely shared data.\n",{"id":6461,"difficulty":63,"q":6462,"a":6463},"form-generic-handler","How do you manage many form fields with one state object?","Hold the fields in one object and use a generic change handler keyed by the\ninput's `name`, spreading the previous object to preserve the other fields.\n\n```jsx\nconst [form, setForm] = useState({ name: '', email: '' })\nconst onChange = e =>\n  setForm(prev => ({ ...prev, [e.target.name]: e.target.value }))\n\n\u003Cinput name=\"email\" value={form.email} onChange={onChange} \u002F>\n```\n\nThe computed key `[e.target.name]` updates just one field. For large\u002Fvalidated\nforms, a form library or `useReducer` scales better than hand-rolling this.\n",{"id":6465,"difficulty":63,"q":6466,"a":6467},"no-setstate-callback","Is there a setState callback like in class components?","No. The class `this.setState(value, callback)` second argument doesn't exist for\nthe `useState` setter. To run code **after** a state update commits, use a\n`useEffect` that depends on that state.\n\n```jsx\nconst [count, setCount] = useState(0)\nuseEffect(() => {\n  \u002F\u002F runs after the render caused by count changing\n  analytics.track(count)\n}, [count])\n```\n\nThis is the hooks way to \"do X after state changes\" — react to the new value in\nan effect rather than passing a callback to the setter.\n",{"id":6469,"difficulty":71,"q":6470,"a":6471},"number-input","How do you handle number inputs with useState?","An `\u003Cinput>`'s value is always a **string**, so convert it when you need a\nnumber, and decide how to handle empty\u002Finvalid input.\n\n```jsx\nconst [age, setAge] = useState('')\n\u003Cinput\n  type=\"number\"\n  value={age}\n  onChange={e => setAge(e.target.value)} \u002F\u002F keep the raw string in state\n\u002F>\nconst ageNum = age === '' ? 0 : Number(age) \u002F\u002F parse where you use it\n```\n\nStoring the raw string avoids fighting the input (e.g. a partially typed `-` or\n`.`), and you parse to a number only at the point of use.\n",{"id":6473,"difficulty":84,"q":6474,"a":6475},"batched-puzzle","What does calling the same setter three times with the value form produce?","```jsx\nconst [count, setCount] = useState(0)\nfunction handle() {\n  setCount(count + 1)\n  setCount(count + 1)\n  setCount(count + 1)\n} \u002F\u002F after one click, count is 1 — not 3\n```\n\nAll three read the **same** `count` (0) from this render's closure, each\ncomputing `1`, and batching collapses them to a single update of `1`. Use the\nfunctional form to actually add 3:\n\n```jsx\nsetCount(c => c + 1) \u002F\u002F ×3 -> each receives the previous result -> 3\n```\n\nThis puzzle tests whether you understand closures-over-state plus batching.\n",{"description":61},"React useState interview questions — state updates, batching, functional updates, lazy initialization and why state seems one render behind.","react\u002Fhooks\u002Fusestate","useState","ecZdz3Hz9vchxC3tS5HAVYkPMt3Vp8u1wGhzVLUHQ4Q",{"id":6482,"title":6483,"body":6484,"description":61,"difficulty":63,"extension":64,"framework":39,"frameworkSlug":41,"meta":6488,"navigation":66,"order":12,"path":6489,"questions":6490,"related":207,"seo":6623,"seoDescription":6624,"stem":6625,"subtopic":6483,"topic":6626,"topicSlug":6627,"updated":1525,"__hash__":6628},"qa\u002Fsql\u002Fbasics\u002Fjoins.md","Joins",{"type":58,"value":6485,"toc":6486},[],{"title":61,"searchDepth":22,"depth":22,"links":6487},[],{},"\u002Fsql\u002Fbasics\u002Fjoins",[6491,6495,6499,6503,6507,6511,6515,6519,6523,6527,6531,6535,6539,6543,6547,6551,6555,6559,6563,6567,6571,6575,6579,6583,6587,6591,6595,6599,6603,6607,6611,6615,6619],{"id":6492,"difficulty":71,"q":6493,"a":6494},"what-is-join","What is a JOIN?","A JOIN combines rows from **two or more tables** into one result set, matching\nthem on a **related column** (typically a foreign key referencing a primary\nkey). Relational databases store data in *normalized* tables to avoid\nduplication; joins are how you stitch that data back together at query time.\n\n```sql\n-- users(id, name)  and  orders(id, user_id, total)\nSELECT users.name, orders.total\nFROM users\nJOIN orders ON orders.user_id = users.id;\n```\n\nThe `ON` clause is the **join condition** — it decides which rows from the left\ntable pair with which rows from the right. The *type* of join (INNER, LEFT,\netc.) then decides what to do with rows that have **no match**.\n",{"id":6496,"difficulty":63,"q":6497,"a":6498},"inner-vs-outer","What is the difference between INNER JOIN and OUTER JOIN?","The difference is what happens to **unmatched rows**:\n\n- **`INNER JOIN`** returns **only** rows that have a match in *both* tables.\n  Rows with no counterpart are dropped from the result.\n- **`OUTER JOIN`** (LEFT \u002F RIGHT \u002F FULL) **keeps unmatched rows** from one or\n  both sides, filling the missing columns with **`NULL`**.\n\n```sql\n-- only users who have placed at least one order\nSELECT u.name, o.total\nFROM users u\nINNER JOIN orders o ON o.user_id = u.id;\n\n-- every user, with NULLs for those who never ordered\nSELECT u.name, o.total\nFROM users u\nLEFT OUTER JOIN orders o ON o.user_id = u.id;\n```\n\nThink of INNER as the **intersection** and OUTER as \"intersection **plus** the\nleftovers from the chosen side(s).\" (`INNER` and `OUTER` are optional keywords —\n`JOIN` alone means `INNER JOIN`, and `LEFT JOIN` means `LEFT OUTER JOIN`.)\n",{"id":6500,"difficulty":63,"q":6501,"a":6502},"left-vs-right","What is the difference between LEFT and RIGHT JOIN?","Both are outer joins; they differ only in **which side is preserved**:\n\n- **`LEFT JOIN`** keeps **all rows from the left** (first) table, plus matching\n  rows from the right — unmatched right columns become `NULL`.\n- **`RIGHT JOIN`** keeps **all rows from the right** (second) table, plus\n  matches from the left.\n\nThey're **mirror images**: any RIGHT JOIN can be rewritten as a LEFT JOIN by\nswapping the table order, which is why teams often standardize on LEFT JOIN for\nreadability.\n\n```sql\n-- these two return the same rows\nSELECT u.name, o.id FROM users u LEFT  JOIN orders o ON o.user_id = u.id;\nSELECT u.name, o.id FROM orders o RIGHT JOIN users  u ON o.user_id = u.id;\n```\n",{"id":6504,"difficulty":84,"q":6505,"a":6506},"self-join","What is a self join?","A self join is a table **joined to itself**, using **table aliases** to treat\nthe one physical table as two logical ones. It's the standard way to relate\nrows *within* the same table — most classically, **hierarchies** where a row\npoints to another row in the same table.\n\n```sql\n-- employees(id, name, manager_id) where manager_id -> employees.id\nSELECT e.name AS employee, m.name AS manager\nFROM employees e\nLEFT JOIN employees m ON e.manager_id = m.id;\n```\n\nHere `e` is the \"employee\" view of the table and `m` is the \"manager\" view.\nUsing `LEFT JOIN` keeps top-level employees (whose `manager_id` is `NULL`) in\nthe result with a `NULL` manager. Aliases are **mandatory** — without them the\ncolumn references would be ambiguous.\n",{"id":6508,"difficulty":63,"q":6509,"a":6510},"cross-join","What does a CROSS JOIN produce?","A `CROSS JOIN` returns the **Cartesian product**: every row of the first table\npaired with **every** row of the second, with **no `ON` condition**. If the\ntables have *M* and *N* rows, you get *M × N* rows back — so it grows fast.\n\n```sql\n-- generate every size\u002Fcolor combination\nSELECT s.label, c.name\nFROM sizes s\nCROSS JOIN colors c;   -- 4 sizes × 6 colors = 24 rows\n```\n\nUse it deliberately — for generating combinations, building calendars, or\ncreating test data. An **accidental** cross join (forgetting the join\ncondition, the dreaded \"comma join\" `FROM a, b`) is a common cause of\nrunaway result sets and slow queries.\n",{"id":6512,"difficulty":84,"q":6513,"a":6514},"join-nulls","How do you find rows with no match using a join?","Use the **anti-join** pattern: `LEFT JOIN` the second table, then filter where\nits key **`IS NULL`**. Because unmatched rows get `NULL` in the right-hand\ncolumns, \"right key is NULL\" precisely selects the rows that had **no match**.\n\n```sql\n-- users who have never placed an order\nSELECT u.*\nFROM users u\nLEFT JOIN orders o ON o.user_id = u.id\nWHERE o.id IS NULL;\n```\n\nTwo things to get right: filter on a column that's **non-nullable in the source\ntable** (like the right table's primary key `o.id`) so a `NULL` there truly\nmeans \"no row matched,\" and remember you must use **`IS NULL`**, never\n`= NULL` — in SQL, `anything = NULL` evaluates to `unknown`, never `true`.\n`NOT EXISTS` is an equivalent and often clearer alternative.\n",{"id":6516,"difficulty":84,"q":6517,"a":6518},"on-vs-where","What is the difference between the ON and WHERE clauses in a join?","`ON` defines **how rows are matched** (it runs *during* the join); `WHERE` filters\nthe **result** *after* the join. For **INNER** joins they're often\ninterchangeable, but for **OUTER** joins they behave very differently.\n\n```sql\n-- keeps all users; only joins orders with amount > 100\nSELECT u.name, o.amount\nFROM users u\nLEFT JOIN orders o ON o.user_id = u.id AND o.amount > 100;\n\n-- effectively INNER: WHERE drops users whose joined row is NULL\nSELECT u.name, o.amount\nFROM users u\nLEFT JOIN orders o ON o.user_id = u.id\nWHERE o.amount > 100;\n```\n\nPut conditions on the **joined (right) table** in `ON` to preserve outer rows; put\nthem in `WHERE` to filter the final result.\n",{"id":6520,"difficulty":84,"q":6521,"a":6522},"left-join-where-trap","Why does filtering the right table in WHERE turn a LEFT JOIN into an INNER JOIN?","An outer join fills unmatched right-table columns with `NULL`. A `WHERE` condition\non those columns (other than `IS NULL`) evaluates to `unknown` for the unmatched\nrows and **removes them** — silently converting your LEFT JOIN into an INNER JOIN.\n\n```sql\n-- unmatched users have o.status = NULL -> WHERE drops them\nSELECT u.name, o.status\nFROM users u\nLEFT JOIN orders o ON o.user_id = u.id\nWHERE o.status = 'shipped';\n\n-- move the predicate into ON to keep all users\nLEFT JOIN orders o ON o.user_id = u.id AND o.status = 'shipped';\n```\n\nThis is one of the most common SQL bugs. Rule: predicates on the optional side\nbelong in `ON`.\n",{"id":6524,"difficulty":63,"q":6525,"a":6526},"multiple-joins","How do you join three or more tables?","Chain `JOIN` clauses; each `ON` connects the new table to one already in the query.\nThe joins are applied left to right, building a progressively wider result.\n\n```sql\nSELECT u.name, o.id AS order_id, p.name AS product\nFROM users u\nJOIN orders o      ON o.user_id = u.id\nJOIN order_items i ON i.order_id = o.id\nJOIN products p    ON p.id = i.product_id;\n```\n\nEach join multiplies\u002Ffilters rows based on its matches, so a user with many orders\nand items appears on many rows. Mind the cardinality — joining several\none-to-many tables can explode row counts (the \"fan trap\").\n",{"id":6528,"difficulty":63,"q":6529,"a":6530},"using-clause","What does the USING clause do?","`USING (col)` is shorthand for an equi-join when the join columns have the **same\nname** in both tables: `USING (user_id)` ≡ `ON a.user_id = b.user_id`. It also\n**merges** the shared column into one in the output.\n\n```sql\nSELECT name, amount\nFROM users\nJOIN orders USING (user_id);   -- one user_id column in the result\n```\n\nCleaner than repeating the column, but only works when names match exactly, and\nthe coalesced column can't be qualified with a table alias. `ON` is more explicit\nand flexible.\n",{"id":6532,"difficulty":84,"q":6533,"a":6534},"natural-join","What is a NATURAL JOIN and why is it risky?","`NATURAL JOIN` automatically joins on **all columns with the same name** in both\ntables — no `ON` needed. It's dangerous because the join condition is **implicit**:\nadding a same-named column later (like `created_at`) silently changes the join.\n\n```sql\nSELECT * FROM users NATURAL JOIN orders;\n-- joins on EVERY shared column name — fragile and surprising\n```\n\nA new `updated_at` column on both tables would suddenly become part of the join\ncondition, breaking results with no error. Most teams **avoid** `NATURAL JOIN` in\nfavor of explicit `ON`\u002F`USING`.\n",{"id":6536,"difficulty":63,"q":6537,"a":6538},"join-groupby","How do you combine a join with aggregation?","Join the tables, then `GROUP BY` the dimension you want to aggregate per, applying\naggregate functions to the joined rows. With outer joins, choose `COUNT(column)`\nvs `COUNT(*)` carefully (next question).\n\n```sql\nSELECT u.name, COUNT(o.id) AS order_count, COALESCE(SUM(o.amount), 0) AS total\nFROM users u\nLEFT JOIN orders o ON o.user_id = u.id\nGROUP BY u.id, u.name;\n```\n\nThe `LEFT JOIN` keeps users with zero orders (counted as 0). Every non-aggregated\nselected column must appear in `GROUP BY` (in standard SQL).\n",{"id":6540,"difficulty":63,"q":6541,"a":6542},"duplicate-rows","Why do joins sometimes produce duplicate rows?","A join produces a row for **every matching pair**. If one side matches **multiple**\nrows on the other (a one-to-many relationship), the single-side values repeat\nacross those matches — not true duplicates, but multiplied rows.\n\n```sql\n-- a user with 3 orders appears on 3 rows\nSELECT u.name, o.id\nFROM users u\nJOIN orders o ON o.user_id = u.id;\n```\n\nTo collapse them, aggregate (`GROUP BY` + `COUNT`\u002F`SUM`), use `DISTINCT`, or\npre-aggregate the many-side in a subquery before joining. Joining two\none-to-many tables to the same parent multiplies rows (the fan trap).\n",{"id":6544,"difficulty":84,"q":6545,"a":6546},"left-join-count-trap","What is the COUNT trap with LEFT JOIN?","`COUNT(*)` counts **rows**, including the NULL-filled row produced for an unmatched\nLEFT JOIN — so users with no orders wrongly count as 1. `COUNT(column)` ignores\n`NULL`s, giving the correct 0.\n\n```sql\nSELECT u.name,\n       COUNT(*)    AS wrong,   -- counts the NULL row -> 1 for zero-order users\n       COUNT(o.id) AS correct  -- ignores NULLs -> 0\nFROM users u\nLEFT JOIN orders o ON o.user_id = u.id\nGROUP BY u.id, u.name;\n```\n\nAlways `COUNT` a **non-nullable column from the joined table** (like its primary\nkey) when counting matches in an outer join.\n",{"id":6548,"difficulty":63,"q":6549,"a":6550},"join-vs-subquery","When should you use a join vs a subquery?","Use a **join** when you need **columns from both tables** in the output. Use a\n**subquery** (especially `EXISTS`\u002F`IN`) when you only need to **filter** by the\nexistence of related rows, not return their columns.\n\n```sql\n-- join: need order data in the result\nSELECT u.name, o.amount FROM users u JOIN orders o ON o.user_id = u.id;\n\n-- subquery: only filter users who have any order\nSELECT name FROM users u WHERE EXISTS (\n  SELECT 1 FROM orders o WHERE o.user_id = u.id\n);\n```\n\nA join can produce duplicate rows when filtering by existence; `EXISTS` won't.\nModern optimizers often plan them similarly, so favor whichever is clearer.\n",{"id":6552,"difficulty":84,"q":6553,"a":6554},"exists-vs-in","What is the difference between EXISTS and IN?","Both test membership, but: `EXISTS` stops at the **first match** (often faster for\nlarge\u002Fcorrelated subqueries) and handles `NULL`s safely. `IN` compares against a\nvalue list and has a **NULL trap** — `NOT IN` with any `NULL` in the list returns\nno rows.\n\n```sql\n-- if any user_id is NULL, NOT IN returns NOTHING\nSELECT * FROM users WHERE id NOT IN (SELECT user_id FROM orders);\n\n-- NOT EXISTS is NULL-safe\nSELECT * FROM users u WHERE NOT EXISTS (\n  SELECT 1 FROM orders o WHERE o.user_id = u.id\n);\n```\n\nPrefer `EXISTS`\u002F`NOT EXISTS` for correlated existence checks, especially when\n`NULL`s are possible.\n",{"id":6556,"difficulty":63,"q":6557,"a":6558},"not-exists-antijoin","How do you write an anti-join?","An anti-join returns rows from the first table that have **no match** in the\nsecond. Two idioms: `NOT EXISTS`, or `LEFT JOIN ... WHERE right.key IS NULL`.\n\n```sql\n-- products never ordered (NOT EXISTS)\nSELECT p.* FROM products p\nWHERE NOT EXISTS (\n  SELECT 1 FROM order_items i WHERE i.product_id = p.id\n);\n\n-- equivalent LEFT JOIN form\nSELECT p.* FROM products p\nLEFT JOIN order_items i ON i.product_id = p.id\nWHERE i.product_id IS NULL;\n```\n\n`NOT EXISTS` is usually clearest and NULL-safe; the LEFT JOIN form can be faster\nwith the right indexes. Avoid `NOT IN` here due to its NULL trap.\n",{"id":6560,"difficulty":84,"q":6561,"a":6562},"semi-join","What is a semi-join?","A semi-join returns rows from the first table that have **at least one match** in\nthe second — but **without** duplicating them per match and without returning the\nsecond table's columns. `EXISTS`\u002F`IN` express it.\n\n```sql\n-- users who have placed at least one order (each user once)\nSELECT u.* FROM users u\nWHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);\n```\n\nContrast with an inner join, which would repeat a user once per order. Semi-join =\n\"filter by existence.\" Anti-join = \"filter by non-existence.\" Databases have\ndedicated semi\u002Fanti-join operators for these.\n",{"id":6564,"difficulty":63,"q":6565,"a":6566},"full-outer-join","What does a FULL OUTER JOIN do?","A `FULL OUTER JOIN` keeps **all rows from both tables**, matching where possible\nand filling the non-matching side with `NULL`s. It's the union of LEFT and RIGHT\nouter joins.\n\n```sql\nSELECT COALESCE(a.id, b.id) AS id, a.val AS left_val, b.val AS right_val\nFROM table_a a\nFULL OUTER JOIN table_b b ON a.id = b.id;\n```\n\nUseful for reconciliation (\"what's in either source\"), like comparing two datasets\nand finding rows present in one but not the other. Supported in PostgreSQL\u002FSQL\nServer\u002FOracle, but **not** in MySQL (which needs an emulation).\n",{"id":6568,"difficulty":84,"q":6569,"a":6570},"emulate-full-outer","How do you emulate a FULL OUTER JOIN in MySQL?","MySQL lacks `FULL OUTER JOIN`, so you **UNION a LEFT JOIN with a RIGHT JOIN** (or a\nLEFT JOIN where the left key is NULL), using `UNION` to dedupe the overlapping\nmatched rows.\n\n```sql\nSELECT a.id, a.val, b.val FROM a LEFT JOIN b ON a.id = b.id\nUNION\nSELECT b.id, a.val, b.val FROM a RIGHT JOIN b ON a.id = b.id;\n```\n\n`UNION` (not `UNION ALL`) removes the duplicate matched rows that appear in both\nhalves. The first half gives all left rows + matches; the second adds the\nunmatched right rows.\n",{"id":6572,"difficulty":63,"q":6573,"a":6574},"equi-non-equi","What is the difference between an equi-join and a non-equi join?","An **equi-join** matches with equality (`a.x = b.x`) — by far the most common. A\n**non-equi join** uses other operators (`\u003C`, `>`, `BETWEEN`, `!=`), useful for\nranges, bands, and comparisons.\n\n```sql\n-- non-equi: match each sale to its price tier by range\nSELECT s.amount, t.label\nFROM sales s\nJOIN tiers t ON s.amount BETWEEN t.min_amount AND t.max_amount;\n```\n\nNon-equi joins can match many rows and are costlier (no simple hash join), but\nthey're powerful for bucketing, gaps-and-islands, and \"find rows within a range\"\nproblems.\n",{"id":6576,"difficulty":71,"q":6577,"a":6578},"join-multiple-columns","How do you join on multiple columns?","Combine the conditions in the `ON` clause with `AND` — all must match. This is\ncommon for **composite keys** or matching on several attributes.\n\n```sql\nSELECT *\nFROM order_items i\nJOIN inventory v\n  ON v.product_id = i.product_id\n AND v.warehouse_id = i.warehouse_id;\n```\n\nEvery `AND` condition tightens the match. If the columns share names across both\ntables, `USING (product_id, warehouse_id)` is a shorthand. Make sure composite-key\ncolumns are indexed together for performance.\n",{"id":6580,"difficulty":84,"q":6581,"a":6582},"self-join-consecutive","How do you use a self join to compare consecutive rows?","Join a table to itself on a key offset by one (e.g. matching `id = id + 1`, or\nusing a date difference) to put each row next to its neighbor — useful for\ncomputing differences between sequential records.\n\n```sql\nSELECT a.day, b.sales - a.sales AS daily_change\nFROM daily a\nJOIN daily b ON b.day = a.day + INTERVAL '1 day';\n```\n\nModern SQL often replaces this with **window functions** (`LAG`\u002F`LEAD`), which are\ncleaner and faster, but the self-join technique is the classic approach and still\nappears in interviews.\n",{"id":6584,"difficulty":84,"q":6585,"a":6586},"fan-trap","What is the fan trap (row multiplication) in joins?","The fan trap occurs when you join one parent to **two different one-to-many**\nchild tables. Their rows multiply against each other (a partial Cartesian\nproduct), inflating aggregates like `SUM`.\n\n```sql\n-- orders × shipments multiply; SUM(amount) is overcounted\nSELECT o.id, SUM(p.amount), SUM(s.weight)\nFROM orders o\nJOIN payments p  ON p.order_id = o.id\nJOIN shipments s ON s.order_id = o.id\nGROUP BY o.id;\n```\n\nFix by **pre-aggregating** each child in its own subquery before joining, so each\ncontributes a single row per parent. Always sanity-check counts when joining\nmultiple one-to-many tables.\n",{"id":6588,"difficulty":84,"q":6589,"a":6590},"pre-aggregate","Why and how do you pre-aggregate before joining?","Pre-aggregating collapses a one-to-many child to **one row per key** in a subquery,\nso the subsequent join doesn't multiply rows or distort aggregates (avoiding the\nfan trap and double counting).\n\n```sql\nSELECT u.name, o.order_count, o.total\nFROM users u\nLEFT JOIN (\n  SELECT user_id, COUNT(*) AS order_count, SUM(amount) AS total\n  FROM orders GROUP BY user_id\n) o ON o.user_id = u.id;\n```\n\nNow each user joins to exactly one aggregated order row. This pattern also lets you\ncombine **multiple** independent aggregates without them multiplying together.\n",{"id":6592,"difficulty":84,"q":6593,"a":6594},"join-indexes","How do indexes affect join performance?","Joins match rows on the `ON` columns, so an **index on the join key** (typically\nthe foreign key) lets the database find matches quickly instead of scanning the\nwhole table. Without it, joins degrade to slow full scans.\n\n```sql\nCREATE INDEX idx_orders_user_id ON orders(user_id); -- speeds up the join\nSELECT * FROM users u JOIN orders o ON o.user_id = u.id;\n```\n\nPrimary keys are indexed automatically, but **foreign keys often aren't** — a\nfrequent cause of slow joins. Index both sides of frequent join conditions, and\ncomposite indexes for multi-column joins.\n",{"id":6596,"difficulty":84,"q":6597,"a":6598},"join-algorithms","What join algorithms do databases use?","The optimizer picks among three physical strategies based on data size and\nindexes:\n\n- **Nested loop join** — for each row in one table, look up matches in the other.\n  Great with an index on the inner table; small inputs.\n- **Hash join** — build a hash table on one input, probe with the other. Best for\n  large, unindexed equi-joins.\n- **Merge join** — sort both inputs on the key, then merge. Efficient when inputs\n  are already sorted\u002Findexed.\n\n```sql\nEXPLAIN SELECT * FROM users u JOIN orders o ON o.user_id = u.id;\n-- shows which join algorithm the planner chose\n```\n\nYou don't pick directly, but understanding them (and reading `EXPLAIN`) explains\nwhy a query is slow.\n",{"id":6600,"difficulty":63,"q":6601,"a":6602},"coalesce-join","How do you handle NULLs from outer joins in the output?","Outer joins produce `NULL`s for unmatched rows. Use **`COALESCE`** to substitute a\ndefault (0, '', 'N\u002FA') so results are clean and aggregates behave.\n\n```sql\nSELECT u.name,\n       COALESCE(o.amount, 0)       AS amount,\n       COALESCE(o.status, 'none')  AS status\nFROM users u\nLEFT JOIN orders o ON o.user_id = u.id;\n```\n\n`COALESCE` returns the first non-NULL argument. It's essential after outer joins\nand aggregates (`COALESCE(SUM(x), 0)`) so missing data shows as a sensible value\nrather than `NULL`.\n",{"id":6604,"difficulty":63,"q":6605,"a":6606},"distinct-dedupe","How do you remove duplicate rows from a join result?","A join that matches one-to-many repeats the single-side rows. Options to dedupe:\n`DISTINCT`, aggregation with `GROUP BY`, or restructuring to a semi-join\n(`EXISTS`) when you don't need the joined columns.\n\n```sql\n-- DISTINCT removes exact duplicate rows\nSELECT DISTINCT u.id, u.name\nFROM users u JOIN orders o ON o.user_id = u.id;\n\n-- better when you only want \"users with orders\":\nSELECT u.id, u.name FROM users u\nWHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);\n```\n\nPrefer `EXISTS` over `DISTINCT` when you're really filtering by existence —\n`DISTINCT` does extra sorting\u002Fwork to remove the duplicates the join created.\n",{"id":6608,"difficulty":84,"q":6609,"a":6610},"lateral-join","What is a LATERAL join (or CROSS APPLY)?","A `LATERAL` join (Postgres) \u002F `CROSS APPLY` (SQL Server) lets a subquery in the\n`FROM` clause **reference columns from preceding tables** in the same `FROM` — so\nit runs per outer row. Ideal for \"top-N per group.\"\n\n```sql\n-- each user's 3 most recent orders\nSELECT u.name, o.id, o.created_at\nFROM users u\nCROSS JOIN LATERAL (\n  SELECT id, created_at FROM orders\n  WHERE user_id = u.id            -- references the outer u\n  ORDER BY created_at DESC LIMIT 3\n) o;\n```\n\nRegular subqueries can't see outer `FROM` columns; `LATERAL` can, making\nper-row\u002Fper-group derived tables possible.\n",{"id":6612,"difficulty":84,"q":6613,"a":6614},"outer-join-chain","What happens when you chain outer joins across three tables?","Join order and type matter. A `LEFT JOIN` followed by an `INNER JOIN` on the\noptional table can **drop** the preserved rows, because the inner join requires a\nmatch the NULL-filled rows don't have.\n\n```sql\n-- the INNER JOIN re-filters out users with no orders\nSELECT u.name, oi.qty\nFROM users u\nLEFT JOIN orders o      ON o.user_id = u.id\nJOIN order_items oi     ON oi.order_id = o.id;  -- inner -> drops NULL o.id\n\n-- keep it LEFT all the way down\nLEFT JOIN order_items oi ON oi.order_id = o.id;\n```\n\nTo preserve outer rows through a chain, every downstream join on the optional path\nmust also be an outer join.\n",{"id":6616,"difficulty":71,"q":6617,"a":6618},"join-vs-union","What is the difference between a JOIN and a UNION?","A **JOIN** combines tables **horizontally** — adding columns by matching rows. A\n**UNION** combines result sets **vertically** — stacking rows from queries that\nhave the **same columns**.\n\n```sql\n-- JOIN: wider rows (user + their order)\nSELECT u.name, o.amount FROM users u JOIN orders o ON o.user_id = u.id;\n\n-- UNION: more rows (current + archived orders)\nSELECT id, amount FROM orders\nUNION ALL\nSELECT id, amount FROM archived_orders;\n```\n\n`UNION` dedupes; `UNION ALL` keeps duplicates (and is faster). Use JOIN to relate\ntables, UNION to append similar datasets.\n",{"id":6620,"difficulty":84,"q":6621,"a":6622},"range-join","How do you join rows within a date or value range?","Use a non-equi join with `BETWEEN` or comparison operators in `ON` — matching each\nrow to all rows of the other table that fall within a range. Common for\ntime-windows, price tiers, and IP-range lookups.\n\n```sql\n-- attribute each event to the active campaign window it falls in\nSELECT e.id, c.name\nFROM events e\nJOIN campaigns c\n  ON e.occurred_at BETWEEN c.start_at AND c.end_at;\n```\n\nRange joins can match multiple rows and don't use simple hash joins, so they're\nheavier — index the range columns, and ensure ranges don't unintentionally overlap\n(which multiplies rows).\n",{"description":61},"SQL join interview questions — inner vs outer joins, left vs right, self joins and how NULLs behave, with examples.","sql\u002Fbasics\u002Fjoins","Query Basics","basics","1D24_T3jGo4Oh0JqSVvR75PpYEfzw3-UWKgF21mDRPw",1781808671724]