jQuery interview question · Most asked
What does $.extend() do, and what is the prototype pollution risk?
Summary
$.extend(target, ...sources) copies properties from source objects into the target (a shallow merge); $.extend(true, target, ...sources) merges deeply. A deep merge of untrusted input in older jQuery versions could set properties on Object.prototype through a __proto__ key (CVE-2019-11358, fixed in jQuery 3.4.0), polluting every object in the page.
Longer Answer
Prototype pollution can bypass checks (if (user.isAdmin) becomes true for every object) or enable XSS through gadgets in other libraries. Keep jQuery up to date, never deep-merge untrusted JSON into configuration objects, and for copying data prefer structuredClone or the spread operator ({ ...defaults, ...options }) for shallow merges.
Key Points
- Shallow by default; true = deep.
- Deep merging untrusted input polluted prototypes (fixed in 3.4.0).
- Update jQuery; avoid merging untrusted data.
- Spread/structuredClone in modern code.
More most-asked jQuery questions
- How do you make AJAX requests with jQuery?
- What is the difference between .html() and .text(), and why does it matter for security?
- What is event delegation, and why is it useful?
- What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?
- How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
- What is the difference between .attr() and .prop()?
- What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- What is jQuery, and is it still relevant today?