[{"data":1,"prerenderedAt":154},["ShallowReactive",2],{"course-en-immutability":3},{"lesson":4,"number":145,"prev":146,"next":150},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":115,"exercises":126},"immutability",{"ru":7,"en":8},"","Immutability",{"ru":7,"en":10},"Immutability in JavaScript: why mutation breaks code, spread and structuredClone, Object.freeze, non-mutating array methods, R.evolve and the cost of copies.",{"ru":7,"en":12},"Learn to update objects and arrays without mutation, by copying with spread and structuredClone, with non-mutating array methods and with Ramda functions, and understand where a copy is shallow and what it costs.",[14,17,20,22,26,28,30,32,35,37,39,41,44,46,48,50,97,99,102,104,106,109,111,113],{"type":15,"ru":7,"en":16},"text","Immutable data does not change after it is created: to \"change\" an object, you create a new one, and the previous one stays as it was. The \"Pure functions\" lesson already did this: changeAge returned a new user via spread. Here we look at why this is needed, where a copy turns out shallow, how to guard against accidental mutation, and what copies cost.",{"type":18,"ru":7,"en":19},"heading","Why mutation breaks predictability",{"type":15,"ru":7,"en":21},"A variable holding an object or an array holds a reference to it, and assignment or passing it to a function copies the reference, not the object itself. So a variable, a function argument and a field of another object can all point to the same object. If one part of the program changes it, every other part sees the change, and the bug shows up far from where the mutation happened: to find it, you have to work out who else holds a reference to that object.",{"type":23,"code":24},"code",{"ru":7,"en":25},"\u002F\u002F Mutating an argument\n\u002F\u002F ===============================\n\u002F\u002F bestScoreImpure :: [Number] -> Number\n\u002F\u002F IMpure: sort sorts the array that was passed in\nconst bestScoreImpure = (scores) => scores.sort((a, b) => b - a)[0]\n\nconst scores = [40, 95, 70]\nconsole.log(bestScoreImpure(scores)) \u002F\u002F 95\nconsole.log(scores) \u002F\u002F [95, 70, 40]: the original order is lost\n\n\u002F\u002F A shared object\n\u002F\u002F ===============================\nconst defaults = { theme: 'light', fontSize: 14 }\n\nconst userSettings = defaults \u002F\u002F the reference is copied, not the object\nuserSettings.theme = 'dark'\n\nconsole.log(defaults.theme) \u002F\u002F dark: the defaults have changed too\n\n\u002F\u002F Without mutation\n\u002F\u002F ===============================\nconst baseSettings = { theme: 'light', fontSize: 14 }\nconst darkSettings = { ...baseSettings, theme: 'dark' } \u002F\u002F a new object\n\nconsole.log(`${baseSettings.theme} -> ${darkSettings.theme}`) \u002F\u002F light -> dark",{"type":15,"ru":7,"en":27},"const does not help here: it forbids assigning another value to the variable but does not prevent changing the object it points to. Declaring const defaults does not make the object immutable; that takes a copy or Object.freeze.",{"type":18,"ru":7,"en":29},"Shallow and deep copies",{"type":15,"ru":7,"en":31},"Spread creates a new object ({ ...obj }) or array ([...arr]) but copies only the top level: nested objects and arrays stay shared with the original. The same is true of Object.assign({}, obj), arr.slice() and Array.from(arr). To change a nested field safely, you copy every level on the path to it and take the other branches as they are. This is called structural sharing: the new object shares with the old one everything that has not changed.",{"type":23,"code":33},{"ru":7,"en":34},"\u002F\u002F A shallow copy\n\u002F\u002F ===============================\nconst user = { name: 'Anna', address: { city: 'Moscow' }, tags: ['js'] }\n\nconst shallow = { ...user }\nshallow.name = 'Olga' \u002F\u002F the top level was copied: user keeps its name\nshallow.address.city = 'Kazan' \u002F\u002F address is shared: the city changes for user too\n\nconsole.log(user.name) \u002F\u002F Anna\nconsole.log(user.address.city) \u002F\u002F Kazan\n\n\u002F\u002F Copying every level on the path to the change\n\u002F\u002F ===============================\nconst original = { name: 'Anna', address: { city: 'Moscow' }, tags: ['js'] }\n\nconst moved = {\n  ...original,\n  address: { ...original.address, city: 'Kazan' },\n}\n\nconsole.log(original.address.city) \u002F\u002F Moscow\nconsole.log(moved.address.city) \u002F\u002F Kazan\nconsole.log(moved.tags === original.tags) \u002F\u002F true: the unchanged branch is shared\n\n\u002F\u002F A deep copy\n\u002F\u002F ===============================\nconst deep = structuredClone(original)\ndeep.tags.push('fp')\n\nconsole.log(original.tags) \u002F\u002F [\"js\"]\nconsole.log(deep.tags) \u002F\u002F [\"js\", \"fp\"]",{"type":15,"ru":7,"en":36},"structuredClone copies the whole structure to any depth: nested objects and arrays, Date, Map, Set and even circular references. It cannot copy functions and throws a DataCloneError, and a class instance turns into a plain object: the class prototype and methods are lost. JSON.parse(JSON.stringify(obj)) loses more: a Date becomes a string, Map and Set become empty objects, fields holding undefined or functions disappear, and NaN turns into null. structuredClone is available in all major browsers since 2022 and in Node.js since version 17.",{"type":18,"ru":7,"en":38},"Object.freeze",{"type":15,"ru":7,"en":40},"Object.freeze forbids adding, deleting and changing an object's properties and returns the same object. Freezing is shallow: nested objects stay mutable and are frozen separately. What happens on an attempt to write depends on the mode: in sloppy (non-strict) mode the assignment is silently ignored, in strict mode a TypeError is thrown. Code in the course playground runs in non-strict mode, while the code of ES modules (files with import and export) and of class bodies is always strict: there the same write throws a TypeError.",{"type":23,"code":42},{"ru":7,"en":43},"\u002F\u002F Object.freeze\n\u002F\u002F ===============================\nconst config = Object.freeze({ mode: 'prod', limits: { requests: 100 } })\n\n\u002F\u002F non-strict mode: the assignment is silently ignored\nconfig.mode = 'dev'\nconsole.log(config.mode) \u002F\u002F prod\n\n\u002F\u002F strict mode: the same write throws a TypeError\nconst setModeStrict = () => {\n  'use strict'\n  config.mode = 'dev'\n}\n\ntry {\n  setModeStrict()\n} catch (error) {\n  console.log(`strict mode: ${error.name}`) \u002F\u002F strict mode: TypeError\n}\n\n\u002F\u002F array methods throw a TypeError in any mode\nconst frozenList = Object.freeze([1, 2])\n\ntry {\n  frozenList.push(3)\n} catch (error) {\n  console.log(`push: ${error.name}`) \u002F\u002F push: TypeError\n}\n\n\u002F\u002F freezing is shallow: the nested object can still be changed\nconfig.limits.requests = 1\nconsole.log(config.limits.requests) \u002F\u002F 1\nconsole.log(`config: ${Object.isFrozen(config)}, limits: ${Object.isFrozen(config.limits)}`) \u002F\u002F config: true, limits: false",{"type":15,"ru":7,"en":45},"The exception to the non-strict rule is built-in methods: push, sort and other mutating methods on a frozen array always throw a TypeError, because the specification requires them to fail when a write does not succeed. Object.freeze helps catch accidental mutation, but it makes no copies: a new value is still created with spread or structuredClone.",{"type":18,"ru":7,"en":47},"Non-mutating array methods",{"type":15,"ru":7,"en":49},"Some array methods change the array itself: push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin. Others return a new array and leave the original alone: map, filter, concat, slice. ES2023 added non-mutating versions of sorting, reversing, splice and replacing an element.",{"type":51,"caption":52,"columns":54,"rows":61},"table",{"ru":7,"en":53},"Mutating array methods and their non-mutating replacements",[55,57,59],{"ru":7,"en":56},"Task",{"ru":7,"en":58},"Changes the array",{"ru":7,"en":60},"Returns a new array",[62,69,76,83,90],[63,65,67],{"ru":7,"en":64},"Append",{"ru":7,"en":66},"push(x)",{"ru":7,"en":68},"concat(x) or [...arr, x]",[70,72,74],{"ru":7,"en":71},"Sort",{"ru":7,"en":73},"sort(fn)",{"ru":7,"en":75},"toSorted(fn) or [...arr].sort(fn)",[77,79,81],{"ru":7,"en":78},"Reverse",{"ru":7,"en":80},"reverse()",{"ru":7,"en":82},"toReversed() or [...arr].reverse()",[84,86,88],{"ru":7,"en":85},"Remove or insert elements",{"ru":7,"en":87},"splice(start, count, ...items)",{"ru":7,"en":89},"toSpliced(start, count, ...items) or slice and spread",[91,93,95],{"ru":7,"en":92},"Replace an element",{"ru":7,"en":94},"arr[i] = x",{"ru":7,"en":96},"with(i, x) or map",{"type":15,"ru":7,"en":98},"toSorted, toReversed, toSpliced and with became part of the ES2023 standard. They are supported by Chrome and Edge from version 110, Firefox from 115, Safari from 16 and Node.js from 20. If a project has to run in older browsers, copy the array and call the mutating method on the copy ([...arr].sort(fn)), or add a polyfill.",{"type":23,"code":100},{"ru":7,"en":101},"\u002F\u002F Non-mutating array methods\n\u002F\u002F ===============================\nconst scores = [40, 95, 70]\n\n\u002F\u002F bestScore :: [Number] -> Number\n\u002F\u002F toSorted from ES2023 sorts a copy; without ES2023 the same is [...list].sort((a, b) => b - a)[0]\nconst bestScore = (list) => list.toSorted((a, b) => b - a)[0]\n\nconsole.log(bestScore(scores)) \u002F\u002F 95\n\nconst added = scores.concat(60) \u002F\u002F instead of push\nconst replaced = scores.with(1, 90) \u002F\u002F instead of scores[1] = 90\nconst withoutFirst = scores.toSpliced(0, 1) \u002F\u002F instead of splice(0, 1)\nconst reversed = scores.toReversed() \u002F\u002F instead of reverse()\n\nconsole.log(added) \u002F\u002F [40, 95, 70, 60]\nconsole.log(replaced) \u002F\u002F [40, 90, 70]\nconsole.log(withoutFirst) \u002F\u002F [95, 70]\nconsole.log(reversed) \u002F\u002F [70, 95, 40]\nconsole.log(scores) \u002F\u002F [40, 95, 70]: the original array has not changed",{"type":18,"ru":7,"en":103},"Ramda: assoc, assocPath and evolve",{"type":15,"ru":7,"en":105},"Ramda functions do not change their arguments. R.assoc(key, value, obj) returns a copy of the object with the key set to a new value, R.assocPath(path, value, obj) does the same along a nested path, and R.evolve(transformations, obj) applies functions to the listed keys, nested ones included, and leaves the rest as they are. Only the objects on the path to the change are copied; the other branches are shared with the original object, just as with spread by hand. Lenses generalize this idea; they have a lesson of their own, \"Lenses\".",{"type":23,"code":107},{"ru":7,"en":108},"\u002F\u002F assoc, assocPath and evolve come from Ramda: the course playground exposes it as R\n\u002F\u002F ===============================\nconst post = {\n  title: 'Immutability',\n  author: { name: 'Anna', city: 'Moscow' },\n  stats: { views: 10, likes: 2 },\n  tags: ['js'],\n}\n\n\u002F\u002F R.assoc: a copy with a new value for the key\nconst renamed = R.assoc('title', 'Immutable data', post)\n\n\u002F\u002F R.assocPath: a copy with a new value along a nested path\nconst moved = R.assocPath(['author', 'city'], 'Kazan', post)\n\n\u002F\u002F R.evolve: functions for the keys you need, the other keys stay as they are\nconst viewed = R.evolve({ stats: { views: (n) => n + 1 }, tags: (tags) => [...tags, 'fp'] }, post)\n\nconsole.log(renamed.title) \u002F\u002F Immutable data\nconsole.log(moved.author.city) \u002F\u002F Kazan\nconsole.log(viewed.stats.views) \u002F\u002F 11\nconsole.log(viewed.tags) \u002F\u002F [\"js\", \"fp\"]\n\n\u002F\u002F the original post has not changed\nconsole.log(`${post.title}, ${post.author.city}, ${post.stats.views}, ${post.tags.length}`) \u002F\u002F Immutability, Moscow, 10, 1\n\n\u002F\u002F the unchanged branches are shared with the original post\nconsole.log(moved.stats === post.stats) \u002F\u002F true\nconsole.log(viewed.author === post.author) \u002F\u002F true",{"type":18,"ru":7,"en":110},"The cost of copying",{"type":15,"ru":7,"en":112},"A copy is not free: spread walks over every key or element of the top level, and structuredClone over the whole structure. For a single update this goes unnoticed, but in a loop the copies add up. A common trap is reduce with the accumulator [...acc, x]: every step copies the whole accumulated array, so n elements add up to about n²\u002F2 element copies. For 1,000 elements that is 499,500 copies, for 10,000 it is almost 50 million.",{"type":15,"ru":7,"en":114},"Immutability matters at the boundaries, where someone else can see the data. An array that a function created itself and has not handed to anyone yet can safely be filled with push: nobody outside can see it, and the function stays pure. For large, frequently updated collections there are libraries built on structural sharing: Immutable.js with persistent data structures, and Immer, where you write ordinary \"mutating\" code against a draft and get a new object back.",[116,118,120,122,124],{"ru":7,"en":117},"Assignment and passing to a function copy the reference to an object, not the object itself: a mutation in one place is visible wherever there is a reference to the same object. const forbids reassignment, not changing the object.",{"ru":7,"en":119},"Spread, Object.assign and slice copy only the top level. For a nested change, copy every level on the path to it; for a full copy there is structuredClone.",{"ru":7,"en":121},"Object.freeze is shallow: in non-strict mode a write to a frozen property is silently ignored, in strict mode it throws a TypeError.",{"ru":7,"en":123},"Instead of push, sort, reverse and splice, use concat, slice and spread, or the ES2023 methods toSorted, toReversed, toSpliced and with. R.assoc, R.assocPath and R.evolve update objects without mutation.",{"ru":7,"en":125},"Copies cost time and memory: [...acc, x] in reduce leads to quadratic complexity. A local array that nobody else can see yet may be filled with push.",[127,136],{"task":128,"starter":130,"solution":132,"expected":134},{"ru":7,"en":129},"The addScoreImpure and topThreeImpure functions change the array passed to them. Write pure addScore and topThree: the first returns a new array with the score added, the second returns the three best scores in descending order. The original scores array must stay the same.",{"ru":7,"en":131},"\u002F\u002F addScoreImpure :: ([Number], Number) -> [Number]\n\u002F\u002F IMpure: push changes the array passed in\nconst addScoreImpure = (scores, score) => {\n  scores.push(score)\n  return scores\n}\n\n\u002F\u002F topThreeImpure :: [Number] -> [Number]\n\u002F\u002F IMpure: sort sorts the array passed in\nconst topThreeImpure = (scores) => scores.sort((a, b) => b - a).slice(0, 3)\n\n\u002F\u002F addScore :: ([Number], Number) -> [Number]\n\u002F\u002F topThree :: [Number] -> [Number]\n\u002F\u002F your code\n\nconst scores = [40, 95, 70, 85]\nconst updated = addScore(scores, 60)\n\nconsole.log(`top three: ${topThree(updated).join(', ')}`)\nconsole.log(`original array: ${scores.join(', ')}`)\nconsole.log(`new array: ${updated.join(', ')}`)",{"ru":7,"en":133},"\u002F\u002F addScoreImpure :: ([Number], Number) -> [Number]\n\u002F\u002F IMpure: push changes the array passed in\nconst addScoreImpure = (scores, score) => {\n  scores.push(score)\n  return scores\n}\n\n\u002F\u002F topThreeImpure :: [Number] -> [Number]\n\u002F\u002F IMpure: sort sorts the array passed in\nconst topThreeImpure = (scores) => scores.sort((a, b) => b - a).slice(0, 3)\n\n\u002F\u002F addScore :: ([Number], Number) -> [Number]\n\u002F\u002F a new array instead of push\nconst addScore = (scores, score) => [...scores, score]\n\n\u002F\u002F topThree :: [Number] -> [Number]\n\u002F\u002F we sort a copy; in ES2023 scores.toSorted((a, b) => b - a) does the same\nconst topThree = (scores) => [...scores].sort((a, b) => b - a).slice(0, 3)\n\nconst scores = [40, 95, 70, 85]\nconst updated = addScore(scores, 60)\n\nconsole.log(`top three: ${topThree(updated).join(', ')}`)\nconsole.log(`original array: ${scores.join(', ')}`)\nconsole.log(`new array: ${updated.join(', ')}`)",{"ru":7,"en":135},"top three: 95, 85, 70\noriginal array: 40, 95, 70, 85\nnew array: 40, 95, 70, 85, 60",{"task":137,"starter":139,"solution":141,"expected":143},{"ru":7,"en":138},"The moveToImpure function changes the city right inside the state passed to it. Write a pure moveTo(city, state): use spread to copy every level on the path state.user.address. Then write moveToRamda with the same result using R.assocPath. Check that the original state has not changed, the user object is new, and the cart branch you did not touch is still shared.",{"ru":7,"en":140},"const state = {\n  user: { name: 'Anna', address: { city: 'Moscow', zip: '101000' } },\n  cart: [{ title: 'book', qty: 1 }],\n}\n\n\u002F\u002F moveToImpure :: (String, Object) -> Object\n\u002F\u002F IMpure: it changes the state passed in\nconst moveToImpure = (city, state) => {\n  state.user.address.city = city\n  return state\n}\n\n\u002F\u002F moveTo :: (String, Object) -> Object\n\u002F\u002F moveToRamda :: (String, Object) -> Object\n\u002F\u002F your code: moveTo with spread, moveToRamda with R.assocPath\n\nconst next = moveTo('Kazan', state)\n\nconsole.log(`before: ${state.user.address.city}, after: ${next.user.address.city}`)\nconsole.log(`new user: ${next.user !== state.user}`)\nconsole.log(`shared cart: ${next.cart === state.cart}`)\nconsole.log(`R.assocPath gives the same: ${JSON.stringify(moveToRamda('Kazan', state)) === JSON.stringify(next)}`)",{"ru":7,"en":142},"const state = {\n  user: { name: 'Anna', address: { city: 'Moscow', zip: '101000' } },\n  cart: [{ title: 'book', qty: 1 }],\n}\n\n\u002F\u002F moveToImpure :: (String, Object) -> Object\n\u002F\u002F IMpure: it changes the state passed in\nconst moveToImpure = (city, state) => {\n  state.user.address.city = city\n  return state\n}\n\n\u002F\u002F moveTo :: (String, Object) -> Object\n\u002F\u002F new objects only on the path state -> user -> address, cart is taken as it is\nconst moveTo = (city, state) => ({\n  ...state,\n  user: {\n    ...state.user,\n    address: { ...state.user.address, city },\n  },\n})\n\n\u002F\u002F moveToRamda :: (String, Object) -> Object\nconst moveToRamda = (city, state) => R.assocPath(['user', 'address', 'city'], city, state)\n\nconst next = moveTo('Kazan', state)\n\nconsole.log(`before: ${state.user.address.city}, after: ${next.user.address.city}`)\nconsole.log(`new user: ${next.user !== state.user}`)\nconsole.log(`shared cart: ${next.cart === state.cart}`)\nconsole.log(`R.assocPath gives the same: ${JSON.stringify(moveToRamda('Kazan', state)) === JSON.stringify(next)}`)",{"ru":7,"en":144},"before: Moscow, after: Kazan\nnew user: true\nshared cart: true\nR.assocPath gives the same: true",6,{"slug":147,"title":148},"pure-functions",{"ru":7,"en":149},"Pure functions",{"slug":151,"title":152},"hindley-milner-type-notation",{"ru":7,"en":153},"Hindley–Milner type notation",1792684724207]