[{"data":1,"prerenderedAt":1425},["ShallowReactive",2],{"$flkB0iQYF4olNvNoVVVb0xVHnwqcsi96xp8L6iVGRzRw":3,"$fMMUdSFktwQFqMVGPrTtt3EC5yheBp7PzwIqznamFcMo":96,"$f1Prj1xEczHja_-L7FyIGgRHd5_cSWHo7r6AE5aheAik":99,"$fc0LoAJgqXDLbKKd2JS_NpM4SuzBK8EycUXINSg09CKU":424,"$fM3ea55k6lKMPOTM84llDB26VSQDVVbxiQuSBFQw9P_c":427,"$fI5fDmvm-5tr9wcH0eHaKZa1j3y_FQIQaHHPqbZxAHJE":671,"mdc--r538zw-key":691,"mdc-3wqqx6-key":730,"mdc-tocbt6-key":743,"mdc-bjewu4-key":756,"mdc--s1w1mu-key":769,"mdc-mou9c3-key":782,"mdc--f0ya4j-key":822,"mdc--igyyjw-key":850,"mdc--mqip8z-key":868,"mdc--fa1sjb-key":885,"mdc--hn355h-key":1119,"mdc-fspvq-key":1155,"mdc-icx4m1-key":1172,"mdc-x79r98-key":1265,"mdc--22z9rk-key":1317,"mdc--vujjwe-key":1361},{"content":4,"quizQuestionContent":65,"type":84,"pageMeta":85},[5,9,13,16,20,24,27,31,34,37,41,44,48,52,55,59,62],{"id":6,"value":7,"isTypeH1":8},"1942","Замыкание и i-- в while: что выведет console.log",true,{"id":10,"value":11,"anchor":12,"isTypeH2":8},"4491","Разбор кода по шагам","step-by-step-code-walkthrough",{"id":14,"value":15,"isTypeParagraph":8},"10337","Исходный код:\n\n```\nlet i = 10, arr = [];\nwhile (i--) {\n    arr.push(() => i + i);  \n}\nconsole.log([arr[0](), arr[0]()]);\n```",{"id":17,"description":18,"titleAlert":19,"isTypeAlertInfo":8},"680","Постфиксная форма декремента `x--` возвращает старое значение выражения, а уменьшение переменной выполняется сразу после вычисления этого выражения.",null,{"id":21,"value":22,"anchor":23,"isTypeH3":8},"4520","Что делает условие while","what-the-while-condition-does",{"id":25,"value":26,"isTypeParagraph":8},"10338","Условие `while (i--)` проверяет “истинность” по значению `i` до уменьшения, а само уменьшение `i` выполняется после вычисления условия и до выполнения тела цикла.\n\nТрассировка (ключевые моменты):\n\n| Момент | Значение i перед проверкой | Результат выражения `i--` | Входит в цикл? | Значение i внутри тела |\n|---|---:|---:|---|---:|\n| Старт | 10 | 10 | да | 9 |\n| ... | ... | ... | ... | ... |\n| Последний заход | 1 | 1 | да | 0 |\n| Проверка после цикла | 0 | 0 | нет | (тело не выполняется) |\n\nВажно: когда `i` становится 0, выражение `i--` возвращает 0 (это “ложь”), но затем всё равно уменьшает `i` до -1, даже несмотря на то, что тело цикла уже не выполняется.\n\nИтог после завершения `while`: `i` равно -1.\n",{"id":28,"value":29,"anchor":30,"isTypeH3":8},"4521","Что именно кладётся в arr","what-gets-stored-in-arr",{"id":32,"value":33,"isTypeParagraph":8},"10339","В `arr` добавляются функции-замыкания: каждая стрелочная функция сохраняет доступ к лексическому окружению, в котором она была создана (то есть к переменным внешней области видимости).\n\nКлючевая идея: замыкание в JavaScript — это не “снимок” значения переменной, а доступ к самой переменной через лексическое окружение; если переменная меняется, то при вызове функции будет использовано актуальное на момент вызова значение.\n\nСхема (упрощённо):\n\n```\n[внешнее окружение]\n  i  ---> (одна и та же переменная, меняется в while)\n  arr -> [ f0, f1, f2, ... ]\n           |\n           +--> f0: () => i + i  (читает i при вызове)\n```",{"id":35,"description":36,"titleAlert":19,"isTypeAlertWarning":8},"739","Наличие `let` само по себе не гарантирует “новую i на каждой итерации” в любом цикле: если переменная объявлена один раз снаружи, а затем изменяется, то все замыкания будут ссылаться на одну и ту же переменную.",{"id":38,"value":39,"anchor":40,"isTypeH2":8},"4492","Почему результат именно [-2, -2]","why-the-result-is-minus-two",{"id":42,"value":43,"isTypeParagraph":8},"10340","1) После окончания цикла `i` равно -1 (это следует из трассировки условия `while (i--)`).  \n2) `arr[0]` — это функция `() => i + i`, которая при вызове читает текущее значение `i` из внешней области видимости.  \n3) Поэтому при каждом вызове `arr[0]()` вычисляется `-1 + -1`, то есть -2.  \n\nСледовательно, `console.log([arr[0](), arr[0]()]);` выводит `[-2, -2]`.",{"id":45,"value":46,"anchor":47,"isTypeH2":8},"4493","Как получить другие результаты (для понимания)","how-to-get-other-results",{"id":49,"value":50,"anchor":51,"isTypeH3":8},"4522","Вариант A: “зафиксировать” значение в отдельной переменной","variant-a-freeze-value-with-a-new-variable",{"id":53,"value":54,"isTypeParagraph":8},"10341","Идея: внутри тела цикла создать новую константу, равную текущему `i`, и замыкать уже её (то есть “снимок” значения).\n\n```\nlet i = 10, arr = [];\nwhile (i--) {\n    const snapshot = i;\n    arr.push(() => snapshot + snapshot);\n}\nconsole.log([arr[0](), arr[0]()]);\n```\n\nВ этом случае первая функция будет возвращать 18, потому что на первой итерации внутри тела `i` уже стало 9, значит `snapshot` равно 9, и `9 + 9 = 18`.",{"id":56,"value":57,"anchor":58,"isTypeH3":8},"4523","Вариант B: Отличие от `for (let i = ...)`","variant-b-difference-from-for-let-i",{"id":60,"value":61,"isTypeParagraph":8},"10342","При создании замыканий в циклах типичная ошибка связана с тем, что несколько функций могут разделять одно и то же лексическое окружение с изменяемой переменной, из‑за чего при вызове они видят “последнее” значение.\n\nВ конструкции `for (let i = ...)` часто ожидается другое поведение, потому что переменная `i` связана с механизмом итераций цикла `for`; это нередко приводит к тому, что замыкания получают значения “по итерациям”, а не одно общее изменяемое значение. Для `while` с внешней переменной, изменяемой декрементом, такого эффекта по умолчанию нет.",{"id":63,"value":64,"isTypeParagraph":8},"10343","Кратко: в `while (i--)` условие использует старое значение `i`, затем уменьшает `i`, после завершения цикла `i` становится -1; все функции в `arr` читают одну и ту же переменную `i` при вызове, поэтому `arr[0]()` возвращает -2, а итоговый вывод — `[-2, -2]`.",{"id":66,"options":67,"hint":81,"solution":82,"description":83},"1171",[68,72,75,78],{"id":69,"label":70,"isCorrect":71},"4828","`[0, 0]`",false,{"id":73,"label":74,"isCorrect":71},"4829","`[undefined, undefined]`",{"id":76,"label":77,"isCorrect":8},"4830","`[-2, -2]`",{"id":79,"label":80,"isCorrect":71},"4831","`[-1, -1]`","Следует отдельно отследить два факта: (1) как работает условие `i--` (постфиксный декремент), (2) что именно захватывает стрелочная функция `() => i + i` — значение `i` “на момент добавления” или саму переменную `i`.","**Правильный ответ: 3** - ```console.log([arr[0](), arr[0]()])``` выведет ```[-2, -2]```\n","Дан код:\n\n```\nlet i = 10, arr = [];\nwhile (i--) {\n    arr.push(() => i + i);  \n}\nconsole.log([arr[0](), arr[0]()]); \n```\n\nЧто выведет ```console.log```?","quizQuestion",{"title":86,"description":87,"ogTitle":7,"ogDescription":88,"ogImageUrl":89,"canonical":19,"ogLocale":90,"ogSiteName":91,"ogImageType":92,"ogImageWidth":93,"ogImageHeight":94,"ogType":95,"ogUrl":19},"Что выведется в console.log([arr[0](), arr[0]()])?","Разбор замыкания, области видимости let и постдекремента i-- в while, с пошаговой трассировкой и примерами.","Разбор замыкания, области видимости let и постдекремента i-- в while, с трассировкой, схемами и примерами.","/og-image.png","ru_RU","goodwebjob.ru","image_jpeg","1200","630","article",{"siteName":97,"siteUrl":98},"GOOD WEB JOB!","https://goodwebjob.ru",{"slugs":100},[101,104,107,110,113,116,119,122,125,128,131,134,137,140,143,145,148,151,154,157,160,163,166,169,172,175,178,181,184,187,190,193,196,199,202,205,208,211,214,217,220,223,226,229,232,235,238,241,244,247,250,253,256,259,262,265,268,271,274,277,280,283,286,289,292,295,298,301,304,307,310,313,316,319,322,325,328,331,334,337,340,343,346,349,352,355,358,361,364,367,370,373,376,379,382,385,388,391,394,397,400,403,406,409,412,415,418,421],{"name":102,"value":103},"Теоретические задания","theoretical-tasks",{"name":105,"value":106},"Что вернёт этот код: typeof (function(){})()","what-this-code-will-return-typeof-function",{"name":108,"value":109},"С чего начать?","where-to-begin",{"name":111,"value":112},"Почему опасно писать прямо в прототипы базовых типов?","why-is-it-dangerous-to-write-directly-to-the-prototypes-of-basic-types",{"name":114,"value":115},"Backend","backend",{"name":117,"value":118},"Frontend","frontend",{"name":120,"value":121},"Какие логические значения в console.log будут получены?","prototype-what-logical-values-will-be-received-in-console-log",{"name":123,"value":124},"Нечётные числа должны отсортироваться по возрастанию, а чётные должны остаться на своих местах","odd-numbers-should-be-sorted-in-ascending-order-and-even-numbers-should-remain-in-their-original-positions",{"name":126,"value":127}," Найти в массиве неповторяющиеся числа","find-non-repeating-numbers-in-an-array",{"name":129,"value":130},"arr.push(0) повлияет на массив так же, как если бы мы выполнили...","arr-push-0-will-affect-the-array-in-the-same-way-as-if-we-performed",{"name":132,"value":133},"Дана строка: 'one.two.three.four.five'. Необходимо из строки сделать вложенный объект","the-string-one-two-three-four-five-is-given-it-is-necessary-to-make-a-nested-object-out-of-the-string",{"name":135,"value":136},"Реализовать функцию, похоже как в Jquery","implement-a-function-similar-to-jquery",{"name":138,"value":139},"Для каждого вложенного объекта нужно добавить свойство level, которое равняется числу - номер вложенности","for-each-nested-object-you-need-to-add-the-level-property-which-is-equal-to-a-number-the-nesting-number",{"name":141,"value":142},"Какое значение выведет консоль с object.property?","what-value-will-the-console-output-with-object-property",{"name":86,"value":144},"what-will-be-displayed-in-console-log-arr-0-arr-0",{"name":146,"value":147},"Вернуть массив от 1 до n, где числа, кратные 3, заменены на 'fizz', кратные 5 - на 'buzz', а кратные и 3, и 5 одновременно - на 'fizzbuzz'","returns-an-array-from-1-to-n-replacing-numbers-that-are-multiples-of-3-with-fizz-numbers-that-are-multiples-of-5-with-buzz-and-numbers-that-are-multiples-of-both-3-and-5-with-fizzbuzz",{"name":149,"value":150},"Необходимо проверить, являются ли две строки анаграммами друг друга","checks-whether-two-strings-are-anagrams-of-each-other",{"name":152,"value":153},"Определить, является ли слово палиндромом","determines-whether-a-word-is-a-palindrome",{"name":155,"value":156},"Есть массив, в котором лежат объекты с датами, необходимо отсортировать даты по возрастанию","there-is-an-array-containing-objects-with-dates-that-need-to-be-sorted-by-date",{"name":158,"value":159},"Реализовать функцию, принимающую аргументы \"*\", \"1\", \"b\", \"1c\" и возвращающую строку \"1*b*1c\"","implement-a-function-that-accepts-arguments-1-b-1c-and-the-return-string-1-b-1c",{"name":161,"value":162},"Дано дерево (вложенный объект), надо найти сумму всех вершин","given-a-tree-nested-object-it-is-necessary-to-find-the-sum-of-all-vertices",{"name":164,"value":165},"Для каждой ветви дерева записать номер вложенности данной ветви","for-each-branch-of-the-tree-write-down-the-nesting-number-of-this-branch",{"name":167,"value":168},"Есть слова в массиве, необходимо определить, состоят ли они из одних и тех же букв","there-are-words-in-the-array-it-is-necessary-to-determine-whether-they-consist-of-the-same-letters",{"name":170,"value":171},"Числа от 1 до 100 находятся в массиве, они хаотично перемешанные, но в нём не хватает одного числа из этой последовательности. Необходимо найти его","the-numbers-from-1-to-100-are-in-the-array-they-are-randomly-mixed-but-it-lacks-one-number-from-this-sequence-it-is-necessary-to-find-him",{"name":173,"value":174},"Есть строка, состоящая из разных скобок, необходимо проверить, закрыты ли все","there-is-a-string-consisting-of-different-brackets-it-is-necessary-to-check-whether-all-are-closed",{"name":176,"value":177},"Напишите функцию, который сделает из массива объект","write-a-function-that-will-make-an-object-out-of-an-array",{"name":179,"value":180},"Что выведет console.log в результате выполнения цикла while?","what-will-console-log-output-as-a-result-of-executing-the-while-loop",{"name":182,"value":183},"Есть функция и объект. Напишите все известные вам способы, чтобы вывести в консоли значение x из объекта, используя функцию","there-is-a-function-and-an-object-write-all-the-ways-you-know-to-output-the-value-of-x-from-an-object-in-the-console-using-the-function",{"name":185,"value":186},"Что выведет консоль в случае присвоения свойства массиву по строковому отрицательному индексу?","what-will-the-console-display-if-a-property-is-assigned-to-an-array-using-a-negative-string-index",{"name":188,"value":189},"Что выведет консоль в случае удаления элемента массива с помощью оператора delete?","what-will-the-console-output-if-an-array-element-is-deleted-using-the-delete-operator",{"name":191,"value":192},"Уникализация значений в массиве","unifying-values-in-an-array",{"name":194,"value":195},"«Расплющивание» массива","flattening-the-array",{"name":197,"value":198},"Что вернёт метод book.getUpperName()?","what-will-the-book-get-upper-name-method-return",{"name":200,"value":201},"Сжатие строк","string-compression",{"name":203,"value":204},"Что выведет консоль в случае присвоения свойства массиву по строковому положительному индексу?","what-will-the-console-display-if-a-property-is-assigned-to-an-array-using-a-positive-string-index",{"name":206,"value":207},"Что получится в результате передачи объекта как аргумента в функцию и выполнения кода?","what-will-happen-when-an-object-is-passed-as-an-argument-to-a-function-and-the-code-is-executed",{"name":209,"value":210},"Как браузер после ввода домена понимает, откуда брать сайт?","how-does-the-browser-know-where-to-get-the-website-after-entering-the-domain",{"name":212,"value":213},"Как домен попадает в DNS в таблицу соответствия: домен – ip","how-does-a-domain-get-into-the-dns-mapping-table-domain-ip",{"name":215,"value":216},"Как браузер решает, какое соединение ему открывать, TCP или UDP?","how-does-a-browser-decide-whether-to-open-a-tcp-or-udp-connection",{"name":218,"value":219},"Ключевые отличия TCP и UDP","key-differences-between-tcp-and-udp",{"name":221,"value":222},"\"TCP/IP\" - кем является TCP, а кем IP в данном случае?","tcp-ip-who-is-tcp-and-who-is-ip-in-this-case",{"name":224,"value":225},"Что такое HTTP и из чего состоит?","what-is-http-and-what-does-it-consist-of",{"name":227,"value":228},"Что такое заголовки в HTTP и зачем они нужны?","what-are-http-headers-and-why-do-we-need-them",{"name":230,"value":231},"Что такое параметры в HTTP?","what-are-http-parameters",{"name":233,"value":234},"Где находится HTML-код в структуре HTTP-ответа?","where-is-the-html-code-located-in-the-http-response-structure",{"name":236,"value":237},"Что такое HTML?","what-is-html",{"name":239,"value":240},"Чем отличаются 1.0, 1.1, 2.0, 3.0 версии HTTP?","what-are-the-differences-between-http-versions-1-0-1-1-2-0-and-3-0",{"name":242,"value":243},"Пользователь авторизован на сайте. Как сервер узнает об этом с последующими другими заходами, что «я – авторизованный пользователь»?","the-user-is-logged-in-on-the-website-how-does-the-server-know-that-i-am-an-authorized-user-when-the-user-logs-in-again",{"name":245,"value":246},"Что такое cookie?","what-is-a-cookie",{"name":248,"value":249},"Кто является инициатором записи cookie в браузере?","who-initiates-the-cookie-recording-in-the-browser",{"name":251,"value":252},"Есть ли возможность с клиента (с браузера) управлять cookie?","is-it-possible-to-manage-cookies-from-the-client-browser",{"name":254,"value":255},"Лайвкодинг","livecoding",{"name":257,"value":258},"Что вернёт следующий код? Object.create(null).hasOwnProperty('toString')","what-will-the-following-code-return-object-create-null-has-own-property-to-string",{"name":260,"value":261},"Всё, что идет по HTTPS – оно защищено?","is-everything-that-goes-through-https-secure",{"name":263,"value":264},"Все данные зашифрованы, используется https. Хакер взламывает dns и делает подмену одного ip на другой, на фишинговый сайт. В этом случае, злоумышленник может получить данные (логин \\ пароль)?","all-data-is-encrypted-https-is-used-let-s-assume-a-hacker-hacks-the-dns-and-makes-a-substitution-of-one-ip-for-another-a-phishing-site",{"name":266,"value":267},"Есть веб-приложение. Помимо HTTP, какие протоколы того же уровня (Application Layer) можно дополнительно использовать в веб-приложении в браузере?","there-is-a-web-application-in-addition-to-http-what-other-protocols-of-the-same-level-application-layer-can-be-used-in-the-web-application-in-browser",{"name":269,"value":270},"Как браузер парсит JavaScript и изображения при рендеринге?","how-the-browser-parses-javascript-and-images-when-rendering",{"name":272,"value":273},"Что происходит, когда HTTP прислал HTML? Что браузер дальше делает c HTML с учетом того, что она валидная?","what-happens-when-http-sends-html-what-does-the-browser-do-with-this-html-given-that-it-is-valid",{"name":275,"value":276},"Что в браузере блокирует рендеринг страницы?","what-is-blocking-the-page-rendering-in-the-browser",{"name":278,"value":279},"Что такое DOM в браузере? Что такое CSSOM?","what-is-dom-in-a-browser-what-is-cssom",{"name":281,"value":282},"Что является узлами в DOM?","what-are-nodes-in-the-dom",{"name":284,"value":285},"Из чего состоит CSSOM?","what-does-cssom-consist-of",{"name":287,"value":288},"Дан HTML-код. Какой будет цвет у текста «Some dummy text»?","the-html-code-is-given-what-will-be-the-color-of-the-some-dummy-text",{"name":290,"value":291},"Есть шаблон HTML и CSS кода. Какой будет цвет у текста «Таким образом, постоянное»?","there-is-a-template-for-html-and-css-code-what-color-will-the-text-thus-constant-have",{"name":293,"value":294},"Есть шаблон вложенного HTML кода. Какой будет цвет у текста «One more dummy text»?","there-is-a-template-for-embedded-html-code-what-will-be-the-color-of-the-one-more-dummy-text",{"name":296,"value":297},"Есть шаблон вложенного HTML кода. Будет ли display:block у body влиять на span?","there-is-a-template-for-embedded-html-code-will-there-be-a-display-does-bodys-block-affect-span",{"name":299,"value":300},"Есть HTML код. Будет ли font-weight на span влиять?","there-is-an-html-code-will-font-weight-affect-span",{"name":302,"value":303},"Flexbox и Grid, чем отличаются друг от друга?","what-are-the-differences-between-flexbox-and-grid",{"name":305,"value":306},"Заменяют ли Flexbox и Grid друг друга?","do-flexbox-and-grid-replace-each-other",{"name":308,"value":309},"Есть CSS и JS анимация. Какая между ними разница, что быстрее, что более удобно?","there-are-css-and-js-animations-what-is-the-difference-between-them-and-which-is-faster-and-more-convenient",{"name":311,"value":312},"Сборник задач","tasks",{"name":314,"value":315},"Какие способы объявления функции есть в JavaScript?","what-are-the-ways-to-declare-a-function-in-javascript",{"name":317,"value":318},"Что такое this в JavaScript?","what-is-this-in-javascript",{"name":320,"value":321},"Что такое Event Loop, как работает?","what-is-an-event-loop-and-how-does-it-work",{"name":323,"value":324},"Что будет, если вызвать typeof на необъявленной переменной?","what-happens-if-you-call-typeof-on-an-undeclared-variable",{"name":326,"value":327},"Что показывает оператор typeof в JavaScript?","what-does-the-typeof-operator-show-in-javascript",{"name":329,"value":330},"Какие типы данных существует в JavaScript?","what-types-of-data-exist-in-javascript",{"name":332,"value":333},"Какую структуру использовать для хранения упорядоченного списка строк в JavaScript?","what-is-the-best-structure-to-use-for-storing-an-ordered-list-of-strings-in-javascript",{"name":335,"value":336},"Что вернет typeof для массива?","what-will-typeof-return-for-an-array",{"name":338,"value":339},"Почему оператор typeof, применённый к массиву, возвращает объект?","why-does-the-typeof-operator-applied-to-an-array-return-an-object",{"name":341,"value":342},"Если нужно хранить список уникальных строк, какую структуру данных выбрать?","if-you-need-to-store-a-list-of-unique-strings-which-data-structure-should-i-choose",{"name":344,"value":345},"Что возвращает typeof для new Set в JavaScript?","what-does-typeof-return-for-new-set-in-javascript",{"name":347,"value":348},"Для чего нужен React, какие он решает проблемы?","what-is-react-used-for-and-what-problems-does-it-solve",{"name":350,"value":351},"Если убрать в React VDOM/Fiber, и вручную изменять DOM, разве это не оптимально?","if-you-remove-the-vdom-fiber-in-react-and-manually-change-the-dom-isn-t-that-optimal",{"name":353,"value":354},"Есть блок кода. Что в реальном DOM изменится после нажатия на кнопку?","there-is-a-block-of-code-what-changes-in-the-real-dom-after-clicking-the-button",{"name":356,"value":357},"Есть код, в котором список и кнопка. Что в реальном DOM изменится после нажатия на кнопку?","there-is-a-code-in-which-there-is-a-list-and-a-button-what-will-change-in-the-real-dom-after-clicking-on-the-button",{"name":359,"value":360},"Зачем нужен Redux (Mobx/Effector)? Зачем нужен менеджер состояния? Какие проблемы решает?","why-do-we-need-redux-mobx-effector-why-do-we-need-a-state-manager-what-problems-does-it-solve",{"name":362,"value":363},"Как диагностировать и исправить нежелательное изменение цвета фона по клику на кнопку, если исходный код сайта запутан и недоступен для прямого чтения?","how-can-diagnose-and-fix-unwanted-background-color-changes-when-clicking-on-a-button-if-the-source-code-of-the-site-is-confusing-and-inaccessible-to-direct-reading",{"name":365,"value":366},"Разрабатывал, взял закоммитил, запушил. Оказалось, что запушил не в ту ветку, точнее, коммит не в ту ветку. Какие действия?","developed-it-committed-it-and-launched-it-it-turned-out-that-i-had-pushed-it-to-the-wrong-branch-or-rather-the-commit-was-in-the-wrong-branch-what-actions",{"name":368,"value":369},"В git есть несколько вариантов слияния веток, какие? Чем отличаются?","git-has-several-options-for-merging-branches-which-ones-how-are-they-different",{"name":371,"value":372},"Какие существуют стратегии ветвления для работы команды? Что это такое?","what-are-the-branching-strategies-for-the-team-what-is-it",{"name":374,"value":375},"По каким характеристикам, ревьюер понимает, что данный код - хороший, а этот код - плохой?","how-does-a-reviewer-know-which-code-is-good-and-which-code-is-bad",{"name":377,"value":378},"Дан фрагмент bash-скрипта: cd ~; mkdir foo... Что в нем происходит?","here-is-a-fragment-of-a-bash-script-cd-mkdir-foo-what-is-happening-in-this-script",{"name":380,"value":381},"Дан фрагмент bash-скрипта: target=$(ps -Af | grep $1 | head -n 1)...","here-is-a-fragment-of-a-bash-script-target-ps-af-grep-1-head-n-1",{"name":383,"value":384},"Что такое алгоритмическая сложность?","what-is-algorithmic-complexity",{"name":386,"value":387},"Какая алгоритмическая сложность у \"быстрой сортировки\"?","what-is-the-algorithmic-complexity-of-quick-sort",{"name":389,"value":390},"Почему в JavaScript два объекта с одинаковым содержимым при сравнении возвращают false?","why-do-two-objects-with-the-same-content-return-false-when-compared-in-javascript",{"name":392,"value":393},"Каким способом может выполняться авторизация пользователя на сайте?","how-can-a-user-be-authorized-on-a-website",{"name":395,"value":396},"В чем разница между микро- и макро-тасками в JavaScript?","what-is-the-difference-between-micro-and-macro-tasks-in-javascript",{"name":398,"value":399},"В комнате три человека. Какова вероятность того, что хотя бы двое из них одного пола? То есть два и более.","there-are-three-people-in-the-room-what-is-the-probability-that-at-least-two-of-them-are-of-the-same-sex-that-is-two-or-more",{"name":401,"value":402},"Есть монета. Ее подбрасывают пять раз подряд. Каждый раз записывается, что выпало - орел или решка. Сколько разных последовательностей орлов и решек может при этом получиться?","there-is-a-coin-it-is-tossed-five-times-in-a-row-each-time-it-is-recorded-whether-it-lands-on-heads-or-tails-how-many-different-sequences-of-heads-and-tails-can-be-obtained",{"name":404,"value":405},"Как гарантированно найти лёгкую фальшивую монету среди 8 за минимальное число взвешиваний на чашечных весах?","how-can-you-guarantee-to-find-an-easy-fake-coin-among-8-in-the-minimum-number-of-weighings-on-a-balance-scale",{"name":407,"value":408},"Подготовка к тех.интервью","technical-interview",{"name":410,"value":411},"Верно ли утверждение, что злоумышленник, контролирующий роутер и прослушивающий трафик, может получить логины и пароли от сайтов, на которые заходит клиент?","is-it-true-that-an-attacker-who-controls-a-router-and-listens-to-traffic-can-obtain-logins-and-passwords-from-websites-that-a-client-visits",{"name":413,"value":414},"Что такое DNS, как DNS находит нужный IP-адрес?","what-is-dns-and-how-does-dns-find-the-correct-ip-address",{"name":416,"value":417},"Переменные объявлены следующим образом: a=3; b=«hello»;. Укажите правильное утверждение","variables-are-declared-as-follows-specify-the-correct-statement",{"name":419,"value":420},"Какой механизм лежит в основе оптимизации обновлений DOM в React?","what-is-the-underlying-mechanism-for-optimizing-dom-updates-in-react",{"name":422,"value":423},"Что мешает организовать централизованное состояние без менеджера состояния? Если организовать состояние механизмами реакта: контекстом, стейтом, в чем проблема? Что менеджеры состояния привносят?","what-prevents-you-from-organizing-a-centralized-state-without-a-state-manager-if-you-organize-the-state-using-react-context-and-state-mechanisms-what-is-the-problem-what-do-state-managers-add",[425],{"label":407,"slug":408,"to":426},"/technical-interview/where-to-begin",{"navigationList":428,"navigationSublist":434},[429,431],{"path":426,"isActive":71,"name":108,"icon":430,"isNavbarMobileDisabled":8},"material-symbols:visibility-outline-rounded",{"path":432,"isActive":8,"name":311,"icon":433,"isNavbarMobileDisabled":71},"/technical-interview/tasks","material-symbols:task-outline",[435,442,461,470,475,570,587,594,599,642,657,662],{"title":436,"list":437,"isOpened":71},"Bash",[438,440],{"name":377,"path":439,"isActive":71},"/technical-interview/tasks/here-is-a-fragment-of-a-bash-script-cd-mkdir-foo-what-is-happening-in-this-script",{"name":380,"path":441,"isActive":71},"/technical-interview/tasks/here-is-a-fragment-of-a-bash-script-target-ps-af-grep-1-head-n-1",{"title":443,"list":444,"isOpened":71},"CSS",[445,447,449,451,453,455,457,459],{"name":287,"path":446,"isActive":71},"/technical-interview/tasks/the-html-code-is-given-what-will-be-the-color-of-the-some-dummy-text",{"name":290,"path":448,"isActive":71},"/technical-interview/tasks/there-is-a-template-for-html-and-css-code-what-color-will-the-text-thus-constant-have",{"name":293,"path":450,"isActive":71},"/technical-interview/tasks/there-is-a-template-for-embedded-html-code-what-will-be-the-color-of-the-one-more-dummy-text",{"name":296,"path":452,"isActive":71},"/technical-interview/tasks/there-is-a-template-for-embedded-html-code-will-there-be-a-display-does-bodys-block-affect-span",{"name":299,"path":454,"isActive":71},"/technical-interview/tasks/there-is-an-html-code-will-font-weight-affect-span",{"name":302,"path":456,"isActive":71},"/technical-interview/tasks/what-are-the-differences-between-flexbox-and-grid",{"name":305,"path":458,"isActive":71},"/technical-interview/tasks/do-flexbox-and-grid-replace-each-other",{"name":308,"path":460,"isActive":71},"/technical-interview/tasks/there-are-css-and-js-animations-what-is-the-difference-between-them-and-which-is-faster-and-more-convenient",{"title":462,"list":463,"isOpened":71},"Git",[464,466,468],{"name":365,"path":465,"isActive":71},"/technical-interview/tasks/developed-it-committed-it-and-launched-it-it-turned-out-that-i-had-pushed-it-to-the-wrong-branch-or-rather-the-commit-was-in-the-wrong-branch-what-actions",{"name":368,"path":467,"isActive":71},"/technical-interview/tasks/git-has-several-options-for-merging-branches-which-ones-how-are-they-different",{"name":371,"path":469,"isActive":71},"/technical-interview/tasks/what-are-the-branching-strategies-for-the-team-what-is-it",{"title":471,"list":472,"isOpened":71},"HTML",[473],{"name":236,"path":474,"isActive":71},"/technical-interview/tasks/what-is-html",{"title":476,"list":477,"isOpened":71},"JavaScript",[478,480,482,484,486,488,490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522,524,526,528,530,532,534,536,538,540,542,544,546,548,550,552,554,556,558,560,562,564,566,568],{"name":120,"path":479,"isActive":71},"/technical-interview/tasks/prototype-what-logical-values-will-be-received-in-console-log",{"name":111,"path":481,"isActive":71},"/technical-interview/tasks/why-is-it-dangerous-to-write-directly-to-the-prototypes-of-basic-types",{"name":257,"path":483,"isActive":71},"/technical-interview/tasks/what-will-the-following-code-return-object-create-null-has-own-property-to-string",{"name":141,"path":485,"isActive":71},"/technical-interview/tasks/what-value-will-the-console-output-with-object-property",{"name":86,"path":487,"isActive":71},"/technical-interview/tasks/what-will-be-displayed-in-console-log-arr-0-arr-0",{"name":179,"path":489,"isActive":71},"/technical-interview/tasks/what-will-console-log-output-as-a-result-of-executing-the-while-loop",{"name":182,"path":491,"isActive":71},"/technical-interview/tasks/there-is-a-function-and-an-object-write-all-the-ways-you-know-to-output-the-value-of-x-from-an-object-in-the-console-using-the-function",{"name":197,"path":493,"isActive":71},"/technical-interview/tasks/what-will-the-book-get-upper-name-method-return",{"name":416,"path":495,"isActive":71},"/technical-interview/tasks/variables-are-declared-as-follows-specify-the-correct-statement",{"name":203,"path":497,"isActive":71},"/technical-interview/tasks/what-will-the-console-display-if-a-property-is-assigned-to-an-array-using-a-positive-string-index",{"name":185,"path":499,"isActive":71},"/technical-interview/tasks/what-will-the-console-display-if-a-property-is-assigned-to-an-array-using-a-negative-string-index",{"name":188,"path":501,"isActive":71},"/technical-interview/tasks/what-will-the-console-output-if-an-array-element-is-deleted-using-the-delete-operator",{"name":105,"path":503,"isActive":71},"/technical-interview/tasks/what-this-code-will-return-typeof-function",{"name":206,"path":505,"isActive":71},"/technical-interview/tasks/what-will-happen-when-an-object-is-passed-as-an-argument-to-a-function-and-the-code-is-executed",{"name":314,"path":507,"isActive":71},"/technical-interview/tasks/what-are-the-ways-to-declare-a-function-in-javascript",{"name":317,"path":509,"isActive":71},"/technical-interview/tasks/what-is-this-in-javascript",{"name":320,"path":511,"isActive":71},"/technical-interview/tasks/what-is-an-event-loop-and-how-does-it-work",{"name":323,"path":513,"isActive":71},"/technical-interview/tasks/what-happens-if-you-call-typeof-on-an-undeclared-variable",{"name":326,"path":515,"isActive":71},"/technical-interview/tasks/what-does-the-typeof-operator-show-in-javascript",{"name":329,"path":517,"isActive":71},"/technical-interview/tasks/what-types-of-data-exist-in-javascript",{"name":332,"path":519,"isActive":71},"/technical-interview/tasks/what-is-the-best-structure-to-use-for-storing-an-ordered-list-of-strings-in-javascript",{"name":335,"path":521,"isActive":71},"/technical-interview/tasks/what-will-typeof-return-for-an-array",{"name":338,"path":523,"isActive":71},"/technical-interview/tasks/why-does-the-typeof-operator-applied-to-an-array-return-an-object",{"name":341,"path":525,"isActive":71},"/technical-interview/tasks/if-you-need-to-store-a-list-of-unique-strings-which-data-structure-should-i-choose",{"name":344,"path":527,"isActive":71},"/technical-interview/tasks/what-does-typeof-return-for-new-set-in-javascript",{"name":389,"path":529,"isActive":71},"/technical-interview/tasks/why-do-two-objects-with-the-same-content-return-false-when-compared-in-javascript",{"name":395,"path":531,"isActive":71},"/technical-interview/tasks/what-is-the-difference-between-micro-and-macro-tasks-in-javascript",{"name":129,"path":533,"isActive":71},"/technical-interview/tasks/arr-push-0-will-affect-the-array-in-the-same-way-as-if-we-performed",{"name":146,"path":535,"isActive":71},"/technical-interview/tasks/returns-an-array-from-1-to-n-replacing-numbers-that-are-multiples-of-3-with-fizz-numbers-that-are-multiples-of-5-with-buzz-and-numbers-that-are-multiples-of-both-3-and-5-with-fizzbuzz",{"name":132,"path":537,"isActive":71},"/technical-interview/tasks/the-string-one-two-three-four-five-is-given-it-is-necessary-to-make-a-nested-object-out-of-the-string",{"name":161,"path":539,"isActive":71},"/technical-interview/tasks/given-a-tree-nested-object-it-is-necessary-to-find-the-sum-of-all-vertices",{"name":138,"path":541,"isActive":71},"/technical-interview/tasks/for-each-nested-object-you-need-to-add-the-level-property-which-is-equal-to-a-number-the-nesting-number",{"name":164,"path":543,"isActive":71},"/technical-interview/tasks/for-each-branch-of-the-tree-write-down-the-nesting-number-of-this-branch",{"name":155,"path":545,"isActive":71},"/technical-interview/tasks/there-is-an-array-containing-objects-with-dates-that-need-to-be-sorted-by-date",{"name":167,"path":547,"isActive":71},"/technical-interview/tasks/there-are-words-in-the-array-it-is-necessary-to-determine-whether-they-consist-of-the-same-letters",{"name":173,"path":549,"isActive":71},"/technical-interview/tasks/there-is-a-string-consisting-of-different-brackets-it-is-necessary-to-check-whether-all-are-closed",{"name":126,"path":551,"isActive":71},"/technical-interview/tasks/find-non-repeating-numbers-in-an-array",{"name":176,"path":553,"isActive":71},"/technical-interview/tasks/write-a-function-that-will-make-an-object-out-of-an-array",{"name":149,"path":555,"isActive":71},"/technical-interview/tasks/checks-whether-two-strings-are-anagrams-of-each-other",{"name":123,"path":557,"isActive":71},"/technical-interview/tasks/odd-numbers-should-be-sorted-in-ascending-order-and-even-numbers-should-remain-in-their-original-positions",{"name":152,"path":559,"isActive":71},"/technical-interview/tasks/determines-whether-a-word-is-a-palindrome",{"name":194,"path":561,"isActive":71},"/technical-interview/tasks/flattening-the-array",{"name":158,"path":563,"isActive":71},"/technical-interview/tasks/implement-a-function-that-accepts-arguments-1-b-1c-and-the-return-string-1-b-1c",{"name":200,"path":565,"isActive":71},"/technical-interview/tasks/string-compression",{"name":191,"path":567,"isActive":71},"/technical-interview/tasks/unifying-values-in-an-array",{"name":170,"path":569,"isActive":71},"/technical-interview/tasks/the-numbers-from-1-to-100-are-in-the-array-they-are-randomly-mixed-but-it-lacks-one-number-from-this-sequence-it-is-necessary-to-find-him",{"title":571,"list":572,"isOpened":71},"React",[573,575,577,579,581,583,585],{"name":347,"path":574,"isActive":71},"/technical-interview/tasks/what-is-react-used-for-and-what-problems-does-it-solve",{"name":419,"path":576,"isActive":71},"/technical-interview/tasks/what-is-the-underlying-mechanism-for-optimizing-dom-updates-in-react",{"name":350,"path":578,"isActive":71},"/technical-interview/tasks/if-you-remove-the-vdom-fiber-in-react-and-manually-change-the-dom-isn-t-that-optimal",{"name":353,"path":580,"isActive":71},"/technical-interview/tasks/there-is-a-block-of-code-what-changes-in-the-real-dom-after-clicking-the-button",{"name":356,"path":582,"isActive":71},"/technical-interview/tasks/there-is-a-code-in-which-there-is-a-list-and-a-button-what-will-change-in-the-real-dom-after-clicking-on-the-button",{"name":359,"path":584,"isActive":71},"/technical-interview/tasks/why-do-we-need-redux-mobx-effector-why-do-we-need-a-state-manager-what-problems-does-it-solve",{"name":422,"path":586,"isActive":71},"/technical-interview/tasks/what-prevents-you-from-organizing-a-centralized-state-without-a-state-manager-if-you-organize-the-state-using-react-context-and-state-mechanisms-what-is-the-problem-what-do-state-managers-add",{"title":588,"list":589,"isOpened":71},"Алгоритмы",[590,592],{"name":383,"path":591,"isActive":71},"/technical-interview/tasks/what-is-algorithmic-complexity",{"name":386,"path":593,"isActive":71},"/technical-interview/tasks/what-is-the-algorithmic-complexity-of-quick-sort",{"title":595,"list":596,"isOpened":71},"Дебаггинг",[597],{"name":362,"path":598,"isActive":71},"/technical-interview/tasks/how-can-diagnose-and-fix-unwanted-background-color-changes-when-clicking-on-a-button-if-the-source-code-of-the-site-is-confusing-and-inaccessible-to-direct-reading",{"title":600,"list":601,"isOpened":71},"Компьютерные сети",[602,604,606,608,610,612,614,616,618,620,622,624,626,628,630,632,634,636,638,640],{"name":209,"path":603,"isActive":71},"/technical-interview/tasks/how-does-the-browser-know-where-to-get-the-website-after-entering-the-domain",{"name":413,"path":605,"isActive":71},"/technical-interview/tasks/what-is-dns-and-how-does-dns-find-the-correct-ip-address",{"name":212,"path":607,"isActive":71},"/technical-interview/tasks/how-does-a-domain-get-into-the-dns-mapping-table-domain-ip",{"name":215,"path":609,"isActive":71},"/technical-interview/tasks/how-does-a-browser-decide-whether-to-open-a-tcp-or-udp-connection",{"name":218,"path":611,"isActive":71},"/technical-interview/tasks/key-differences-between-tcp-and-udp",{"name":221,"path":613,"isActive":71},"/technical-interview/tasks/tcp-ip-who-is-tcp-and-who-is-ip-in-this-case",{"name":224,"path":615,"isActive":71},"/technical-interview/tasks/what-is-http-and-what-does-it-consist-of",{"name":227,"path":617,"isActive":71},"/technical-interview/tasks/what-are-http-headers-and-why-do-we-need-them",{"name":230,"path":619,"isActive":71},"/technical-interview/tasks/what-are-http-parameters",{"name":233,"path":621,"isActive":71},"/technical-interview/tasks/where-is-the-html-code-located-in-the-http-response-structure",{"name":239,"path":623,"isActive":71},"/technical-interview/tasks/what-are-the-differences-between-http-versions-1-0-1-1-2-0-and-3-0",{"name":242,"path":625,"isActive":71},"/technical-interview/tasks/the-user-is-logged-in-on-the-website-how-does-the-server-know-that-i-am-an-authorized-user-when-the-user-logs-in-again",{"name":245,"path":627,"isActive":71},"/technical-interview/tasks/what-is-a-cookie",{"name":248,"path":629,"isActive":71},"/technical-interview/tasks/who-initiates-the-cookie-recording-in-the-browser",{"name":251,"path":631,"isActive":71},"/technical-interview/tasks/is-it-possible-to-manage-cookies-from-the-client-browser",{"name":410,"path":633,"isActive":71},"/technical-interview/tasks/is-it-true-that-an-attacker-who-controls-a-router-and-listens-to-traffic-can-obtain-logins-and-passwords-from-websites-that-a-client-visits",{"name":260,"path":635,"isActive":71},"/technical-interview/tasks/is-everything-that-goes-through-https-secure",{"name":263,"path":637,"isActive":71},"/technical-interview/tasks/all-data-is-encrypted-https-is-used-let-s-assume-a-hacker-hacks-the-dns-and-makes-a-substitution-of-one-ip-for-another-a-phishing-site",{"name":266,"path":639,"isActive":71},"/technical-interview/tasks/there-is-a-web-application-in-addition-to-http-what-other-protocols-of-the-same-level-application-layer-can-be-used-in-the-web-application-in-browser",{"name":392,"path":641,"isActive":71},"/technical-interview/tasks/how-can-a-user-be-authorized-on-a-website",{"title":643,"list":644,"isOpened":71},"Отрисовка в браузере",[645,647,649,651,653,655],{"name":272,"path":646,"isActive":71},"/technical-interview/tasks/what-happens-when-http-sends-html-what-does-the-browser-do-with-this-html-given-that-it-is-valid",{"name":269,"path":648,"isActive":71},"/technical-interview/tasks/how-the-browser-parses-javascript-and-images-when-rendering",{"name":275,"path":650,"isActive":71},"/technical-interview/tasks/what-is-blocking-the-page-rendering-in-the-browser",{"name":278,"path":652,"isActive":71},"/technical-interview/tasks/what-is-dom-in-a-browser-what-is-cssom",{"name":281,"path":654,"isActive":71},"/technical-interview/tasks/what-are-nodes-in-the-dom",{"name":284,"path":656,"isActive":71},"/technical-interview/tasks/what-does-cssom-consist-of",{"title":658,"list":659,"isOpened":71},"Ревью кода",[660],{"name":374,"path":661,"isActive":71},"/technical-interview/tasks/how-does-a-reviewer-know-which-code-is-good-and-which-code-is-bad",{"title":663,"list":664,"isOpened":71},"Теория вероятности",[665,667,669],{"name":398,"path":666,"isActive":71},"/technical-interview/tasks/there-are-three-people-in-the-room-what-is-the-probability-that-at-least-two-of-them-are-of-the-same-sex-that-is-two-or-more",{"name":401,"path":668,"isActive":71},"/technical-interview/tasks/there-is-a-coin-it-is-tossed-five-times-in-a-row-each-time-it-is-recorded-whether-it-lands-on-heads-or-tails-how-many-different-sequences-of-heads-and-tails-can-be-obtained",{"name":404,"path":670,"isActive":71},"/technical-interview/tasks/how-can-you-guarantee-to-find-an-easy-fake-coin-among-8-in-the-minimum-number-of-weighings-on-a-balance-scale",{"cooperation":672,"copyright":675,"reportError":676,"socialNetwork":678},{"link":673,"title":674},"https://t.me/baurinanton","Сотрудничество","© “GOOD WEB JOB!”",{"label":677,"link":673},"Сообщить об ошибке",{"label":679,"socialNetworkList":680},"Мы в соцсетях:",[681,684,687],{"icon":19,"link":682,"title":683},"https://max.ru/u/f9LHodD0cOKMaukdnnahTeL5pwvjrPfUaZ4S8_1rsNy9I9qsmc9Ar3kP_y8","Max",{"icon":685,"link":673,"title":686},"ic:baseline-telegram","Telegram",{"icon":688,"link":689,"title":690},"ri:vk-fill","https://vk.com/baurinanton","VK",{"data":692,"body":693},{},{"type":694,"children":695},"root",[696,704,717],{"type":697,"tag":698,"props":699,"children":700},"element","p",{},[701],{"type":702,"value":703},"text","Дан код:",{"type":697,"tag":705,"props":706,"children":710},"pre",{"className":707,"code":709,"language":702},[708],"language-text","let i = 10, arr = [];\nwhile (i--) {\n    arr.push(() => i + i);  \n}\nconsole.log([arr[0](), arr[0]()]); \n",[711],{"type":697,"tag":712,"props":713,"children":715},"code",{"__ignoreMap":714},"",[716],{"type":702,"value":709},{"type":697,"tag":698,"props":718,"children":719},{},[720,722,728],{"type":702,"value":721},"Что выведет ",{"type":697,"tag":712,"props":723,"children":725},{"className":724},[],[726],{"type":702,"value":727},"console.log",{"type":702,"value":729},"?",{"data":731,"body":732},{},{"type":694,"children":733},[734],{"type":697,"tag":698,"props":735,"children":736},{},[737],{"type":697,"tag":712,"props":738,"children":740},{"className":739},[],[741],{"type":702,"value":742},"[0, 0]",{"data":744,"body":745},{},{"type":694,"children":746},[747],{"type":697,"tag":698,"props":748,"children":749},{},[750],{"type":697,"tag":712,"props":751,"children":753},{"className":752},[],[754],{"type":702,"value":755},"[undefined, undefined]",{"data":757,"body":758},{},{"type":694,"children":759},[760],{"type":697,"tag":698,"props":761,"children":762},{},[763],{"type":697,"tag":712,"props":764,"children":766},{"className":765},[],[767],{"type":702,"value":768},"[-2, -2]",{"data":770,"body":771},{},{"type":694,"children":772},[773],{"type":697,"tag":698,"props":774,"children":775},{},[776],{"type":697,"tag":712,"props":777,"children":779},{"className":778},[],[780],{"type":702,"value":781},"[-1, -1]",{"data":783,"body":784},{},{"type":694,"children":785},[786],{"type":697,"tag":698,"props":787,"children":788},{},[789,791,797,799,805,807,813,815,820],{"type":702,"value":790},"Следует отдельно отследить два факта: (1) как работает условие ",{"type":697,"tag":712,"props":792,"children":794},{"className":793},[],[795],{"type":702,"value":796},"i--",{"type":702,"value":798}," (постфиксный декремент), (2) что именно захватывает стрелочная функция ",{"type":697,"tag":712,"props":800,"children":802},{"className":801},[],[803],{"type":702,"value":804},"() => i + i",{"type":702,"value":806}," — значение ",{"type":697,"tag":712,"props":808,"children":810},{"className":809},[],[811],{"type":702,"value":812},"i",{"type":702,"value":814}," “на момент добавления” или саму переменную ",{"type":697,"tag":712,"props":816,"children":818},{"className":817},[],[819],{"type":702,"value":812},{"type":702,"value":821},".",{"data":823,"body":824},{},{"type":694,"children":825},[826],{"type":697,"tag":698,"props":827,"children":828},{},[829,835,837,843,845],{"type":697,"tag":830,"props":831,"children":832},"strong",{},[833],{"type":702,"value":834},"Правильный ответ: 3",{"type":702,"value":836}," - ",{"type":697,"tag":712,"props":838,"children":840},{"className":839},[],[841],{"type":702,"value":842},"console.log([arr[0](), arr[0]()])",{"type":702,"value":844}," выведет ",{"type":697,"tag":712,"props":846,"children":848},{"className":847},[],[849],{"type":702,"value":768},{"data":851,"body":852},{},{"type":694,"children":853},[854,859],{"type":697,"tag":698,"props":855,"children":856},{},[857],{"type":702,"value":858},"Исходный код:",{"type":697,"tag":705,"props":860,"children":863},{"className":861,"code":862,"language":702},[708],"let i = 10, arr = [];\nwhile (i--) {\n    arr.push(() => i + i);  \n}\nconsole.log([arr[0](), arr[0]()]);\n",[864],{"type":697,"tag":712,"props":865,"children":866},{"__ignoreMap":714},[867],{"type":702,"value":862},{"data":869,"body":870},{},{"type":694,"children":871},[872],{"type":697,"tag":698,"props":873,"children":874},{},[875,877,883],{"type":702,"value":876},"Постфиксная форма декремента ",{"type":697,"tag":712,"props":878,"children":880},{"className":879},[],[881],{"type":702,"value":882},"x--",{"type":702,"value":884}," возвращает старое значение выражения, а уменьшение переменной выполняется сразу после вычисления этого выражения.",{"data":886,"body":887},{},{"type":694,"children":888},[889,916,921,1073,1099],{"type":697,"tag":698,"props":890,"children":891},{},[892,894,900,902,907,909,914],{"type":702,"value":893},"Условие ",{"type":697,"tag":712,"props":895,"children":897},{"className":896},[],[898],{"type":702,"value":899},"while (i--)",{"type":702,"value":901}," проверяет “истинность” по значению ",{"type":697,"tag":712,"props":903,"children":905},{"className":904},[],[906],{"type":702,"value":812},{"type":702,"value":908}," до уменьшения, а само уменьшение ",{"type":697,"tag":712,"props":910,"children":912},{"className":911},[],[913],{"type":702,"value":812},{"type":702,"value":915}," выполняется после вычисления условия и до выполнения тела цикла.",{"type":697,"tag":698,"props":917,"children":918},{},[919],{"type":702,"value":920},"Трассировка (ключевые моменты):",{"type":697,"tag":922,"props":923,"children":924},"table",{},[925,965],{"type":697,"tag":926,"props":927,"children":928},"thead",{},[929],{"type":697,"tag":930,"props":931,"children":932},"tr",{},[933,939,945,955,960],{"type":697,"tag":934,"props":935,"children":936},"th",{},[937],{"type":702,"value":938},"Момент",{"type":697,"tag":934,"props":940,"children":942},{"align":941},"right",[943],{"type":702,"value":944},"Значение i перед проверкой",{"type":697,"tag":934,"props":946,"children":947},{"align":941},[948,950],{"type":702,"value":949},"Результат выражения ",{"type":697,"tag":712,"props":951,"children":953},{"className":952},[],[954],{"type":702,"value":796},{"type":697,"tag":934,"props":956,"children":957},{},[958],{"type":702,"value":959},"Входит в цикл?",{"type":697,"tag":934,"props":961,"children":962},{"align":941},[963],{"type":702,"value":964},"Значение i внутри тела",{"type":697,"tag":966,"props":967,"children":968},"tbody",{},[969,997,1021,1047],{"type":697,"tag":930,"props":970,"children":971},{},[972,978,983,987,992],{"type":697,"tag":973,"props":974,"children":975},"td",{},[976],{"type":702,"value":977},"Старт",{"type":697,"tag":973,"props":979,"children":980},{"align":941},[981],{"type":702,"value":982},"10",{"type":697,"tag":973,"props":984,"children":985},{"align":941},[986],{"type":702,"value":982},{"type":697,"tag":973,"props":988,"children":989},{},[990],{"type":702,"value":991},"да",{"type":697,"tag":973,"props":993,"children":994},{"align":941},[995],{"type":702,"value":996},"9",{"type":697,"tag":930,"props":998,"children":999},{},[1000,1005,1009,1013,1017],{"type":697,"tag":973,"props":1001,"children":1002},{},[1003],{"type":702,"value":1004},"...",{"type":697,"tag":973,"props":1006,"children":1007},{"align":941},[1008],{"type":702,"value":1004},{"type":697,"tag":973,"props":1010,"children":1011},{"align":941},[1012],{"type":702,"value":1004},{"type":697,"tag":973,"props":1014,"children":1015},{},[1016],{"type":702,"value":1004},{"type":697,"tag":973,"props":1018,"children":1019},{"align":941},[1020],{"type":702,"value":1004},{"type":697,"tag":930,"props":1022,"children":1023},{},[1024,1029,1034,1038,1042],{"type":697,"tag":973,"props":1025,"children":1026},{},[1027],{"type":702,"value":1028},"Последний заход",{"type":697,"tag":973,"props":1030,"children":1031},{"align":941},[1032],{"type":702,"value":1033},"1",{"type":697,"tag":973,"props":1035,"children":1036},{"align":941},[1037],{"type":702,"value":1033},{"type":697,"tag":973,"props":1039,"children":1040},{},[1041],{"type":702,"value":991},{"type":697,"tag":973,"props":1043,"children":1044},{"align":941},[1045],{"type":702,"value":1046},"0",{"type":697,"tag":930,"props":1048,"children":1049},{},[1050,1055,1059,1063,1068],{"type":697,"tag":973,"props":1051,"children":1052},{},[1053],{"type":702,"value":1054},"Проверка после цикла",{"type":697,"tag":973,"props":1056,"children":1057},{"align":941},[1058],{"type":702,"value":1046},{"type":697,"tag":973,"props":1060,"children":1061},{"align":941},[1062],{"type":702,"value":1046},{"type":697,"tag":973,"props":1064,"children":1065},{},[1066],{"type":702,"value":1067},"нет",{"type":697,"tag":973,"props":1069,"children":1070},{"align":941},[1071],{"type":702,"value":1072},"(тело не выполняется)",{"type":697,"tag":698,"props":1074,"children":1075},{},[1076,1078,1083,1085,1090,1092,1097],{"type":702,"value":1077},"Важно: когда ",{"type":697,"tag":712,"props":1079,"children":1081},{"className":1080},[],[1082],{"type":702,"value":812},{"type":702,"value":1084}," становится 0, выражение ",{"type":697,"tag":712,"props":1086,"children":1088},{"className":1087},[],[1089],{"type":702,"value":796},{"type":702,"value":1091}," возвращает 0 (это “ложь”), но затем всё равно уменьшает ",{"type":697,"tag":712,"props":1093,"children":1095},{"className":1094},[],[1096],{"type":702,"value":812},{"type":702,"value":1098}," до -1, даже несмотря на то, что тело цикла уже не выполняется.",{"type":697,"tag":698,"props":1100,"children":1101},{},[1102,1104,1110,1112,1117],{"type":702,"value":1103},"Итог после завершения ",{"type":697,"tag":712,"props":1105,"children":1107},{"className":1106},[],[1108],{"type":702,"value":1109},"while",{"type":702,"value":1111},": ",{"type":697,"tag":712,"props":1113,"children":1115},{"className":1114},[],[1116],{"type":702,"value":812},{"type":702,"value":1118}," равно -1.",{"data":1120,"body":1121},{},{"type":694,"children":1122},[1123,1136,1141,1146],{"type":697,"tag":698,"props":1124,"children":1125},{},[1126,1128,1134],{"type":702,"value":1127},"В ",{"type":697,"tag":712,"props":1129,"children":1131},{"className":1130},[],[1132],{"type":702,"value":1133},"arr",{"type":702,"value":1135}," добавляются функции-замыкания: каждая стрелочная функция сохраняет доступ к лексическому окружению, в котором она была создана (то есть к переменным внешней области видимости).",{"type":697,"tag":698,"props":1137,"children":1138},{},[1139],{"type":702,"value":1140},"Ключевая идея: замыкание в JavaScript — это не “снимок” значения переменной, а доступ к самой переменной через лексическое окружение; если переменная меняется, то при вызове функции будет использовано актуальное на момент вызова значение.",{"type":697,"tag":698,"props":1142,"children":1143},{},[1144],{"type":702,"value":1145},"Схема (упрощённо):",{"type":697,"tag":705,"props":1147,"children":1150},{"className":1148,"code":1149,"language":702},[708],"[внешнее окружение]\n  i  ---> (одна и та же переменная, меняется в while)\n  arr -> [ f0, f1, f2, ... ]\n           |\n           +--> f0: () => i + i  (читает i при вызове)\n",[1151],{"type":697,"tag":712,"props":1152,"children":1153},{"__ignoreMap":714},[1154],{"type":702,"value":1149},{"data":1156,"body":1157},{},{"type":694,"children":1158},[1159],{"type":697,"tag":698,"props":1160,"children":1161},{},[1162,1164,1170],{"type":702,"value":1163},"Наличие ",{"type":697,"tag":712,"props":1165,"children":1167},{"className":1166},[],[1168],{"type":702,"value":1169},"let",{"type":702,"value":1171}," само по себе не гарантирует “новую i на каждой итерации” в любом цикле: если переменная объявлена один раз снаружи, а затем изменяется, то все замыкания будут ссылаться на одну и ту же переменную.",{"data":1173,"body":1174},{},{"type":694,"children":1175},[1176,1246],{"type":697,"tag":1177,"props":1178,"children":1179},"ol",{},[1180,1200,1225],{"type":697,"tag":1181,"props":1182,"children":1183},"li",{},[1184,1186,1191,1193,1198],{"type":702,"value":1185},"После окончания цикла ",{"type":697,"tag":712,"props":1187,"children":1189},{"className":1188},[],[1190],{"type":702,"value":812},{"type":702,"value":1192}," равно -1 (это следует из трассировки условия ",{"type":697,"tag":712,"props":1194,"children":1196},{"className":1195},[],[1197],{"type":702,"value":899},{"type":702,"value":1199},").",{"type":697,"tag":1181,"props":1201,"children":1202},{},[1203,1209,1211,1216,1218,1223],{"type":697,"tag":712,"props":1204,"children":1206},{"className":1205},[],[1207],{"type":702,"value":1208},"arr[0]",{"type":702,"value":1210}," — это функция ",{"type":697,"tag":712,"props":1212,"children":1214},{"className":1213},[],[1215],{"type":702,"value":804},{"type":702,"value":1217},", которая при вызове читает текущее значение ",{"type":697,"tag":712,"props":1219,"children":1221},{"className":1220},[],[1222],{"type":702,"value":812},{"type":702,"value":1224}," из внешней области видимости.",{"type":697,"tag":1181,"props":1226,"children":1227},{},[1228,1230,1236,1238,1244],{"type":702,"value":1229},"Поэтому при каждом вызове ",{"type":697,"tag":712,"props":1231,"children":1233},{"className":1232},[],[1234],{"type":702,"value":1235},"arr[0]()",{"type":702,"value":1237}," вычисляется ",{"type":697,"tag":712,"props":1239,"children":1241},{"className":1240},[],[1242],{"type":702,"value":1243},"-1 + -1",{"type":702,"value":1245},", то есть -2.",{"type":697,"tag":698,"props":1247,"children":1248},{},[1249,1251,1257,1259,1264],{"type":702,"value":1250},"Следовательно, ",{"type":697,"tag":712,"props":1252,"children":1254},{"className":1253},[],[1255],{"type":702,"value":1256},"console.log([arr[0](), arr[0]()]);",{"type":702,"value":1258}," выводит ",{"type":697,"tag":712,"props":1260,"children":1262},{"className":1261},[],[1263],{"type":702,"value":768},{"type":702,"value":821},{"data":1266,"body":1267},{},{"type":694,"children":1268},[1269,1281,1290],{"type":697,"tag":698,"props":1270,"children":1271},{},[1272,1274,1279],{"type":702,"value":1273},"Идея: внутри тела цикла создать новую константу, равную текущему ",{"type":697,"tag":712,"props":1275,"children":1277},{"className":1276},[],[1278],{"type":702,"value":812},{"type":702,"value":1280},", и замыкать уже её (то есть “снимок” значения).",{"type":697,"tag":705,"props":1282,"children":1285},{"className":1283,"code":1284,"language":702},[708],"let i = 10, arr = [];\nwhile (i--) {\n    const snapshot = i;\n    arr.push(() => snapshot + snapshot);\n}\nconsole.log([arr[0](), arr[0]()]);\n",[1286],{"type":697,"tag":712,"props":1287,"children":1288},{"__ignoreMap":714},[1289],{"type":702,"value":1284},{"type":697,"tag":698,"props":1291,"children":1292},{},[1293,1295,1300,1302,1308,1310,1316],{"type":702,"value":1294},"В этом случае первая функция будет возвращать 18, потому что на первой итерации внутри тела ",{"type":697,"tag":712,"props":1296,"children":1298},{"className":1297},[],[1299],{"type":702,"value":812},{"type":702,"value":1301}," уже стало 9, значит ",{"type":697,"tag":712,"props":1303,"children":1305},{"className":1304},[],[1306],{"type":702,"value":1307},"snapshot",{"type":702,"value":1309}," равно 9, и ",{"type":697,"tag":712,"props":1311,"children":1313},{"className":1312},[],[1314],{"type":702,"value":1315},"9 + 9 = 18",{"type":702,"value":821},{"data":1318,"body":1319},{},{"type":694,"children":1320},[1321,1326],{"type":697,"tag":698,"props":1322,"children":1323},{},[1324],{"type":702,"value":1325},"При создании замыканий в циклах типичная ошибка связана с тем, что несколько функций могут разделять одно и то же лексическое окружение с изменяемой переменной, из‑за чего при вызове они видят “последнее” значение.",{"type":697,"tag":698,"props":1327,"children":1328},{},[1329,1331,1337,1339,1344,1346,1352,1354,1359],{"type":702,"value":1330},"В конструкции ",{"type":697,"tag":712,"props":1332,"children":1334},{"className":1333},[],[1335],{"type":702,"value":1336},"for (let i = ...)",{"type":702,"value":1338}," часто ожидается другое поведение, потому что переменная ",{"type":697,"tag":712,"props":1340,"children":1342},{"className":1341},[],[1343],{"type":702,"value":812},{"type":702,"value":1345}," связана с механизмом итераций цикла ",{"type":697,"tag":712,"props":1347,"children":1349},{"className":1348},[],[1350],{"type":702,"value":1351},"for",{"type":702,"value":1353},"; это нередко приводит к тому, что замыкания получают значения “по итерациям”, а не одно общее изменяемое значение. Для ",{"type":697,"tag":712,"props":1355,"children":1357},{"className":1356},[],[1358],{"type":702,"value":1109},{"type":702,"value":1360}," с внешней переменной, изменяемой декрементом, такого эффекта по умолчанию нет.",{"data":1362,"body":1363},{},{"type":694,"children":1364},[1365],{"type":697,"tag":698,"props":1366,"children":1367},{},[1368,1370,1375,1377,1382,1384,1389,1391,1396,1398,1403,1405,1410,1412,1417,1419,1424],{"type":702,"value":1369},"Кратко: в ",{"type":697,"tag":712,"props":1371,"children":1373},{"className":1372},[],[1374],{"type":702,"value":899},{"type":702,"value":1376}," условие использует старое значение ",{"type":697,"tag":712,"props":1378,"children":1380},{"className":1379},[],[1381],{"type":702,"value":812},{"type":702,"value":1383},", затем уменьшает ",{"type":697,"tag":712,"props":1385,"children":1387},{"className":1386},[],[1388],{"type":702,"value":812},{"type":702,"value":1390},", после завершения цикла ",{"type":697,"tag":712,"props":1392,"children":1394},{"className":1393},[],[1395],{"type":702,"value":812},{"type":702,"value":1397}," становится -1; все функции в ",{"type":697,"tag":712,"props":1399,"children":1401},{"className":1400},[],[1402],{"type":702,"value":1133},{"type":702,"value":1404}," читают одну и ту же переменную ",{"type":697,"tag":712,"props":1406,"children":1408},{"className":1407},[],[1409],{"type":702,"value":812},{"type":702,"value":1411}," при вызове, поэтому ",{"type":697,"tag":712,"props":1413,"children":1415},{"className":1414},[],[1416],{"type":702,"value":1235},{"type":702,"value":1418}," возвращает -2, а итоговый вывод — ",{"type":697,"tag":712,"props":1420,"children":1422},{"className":1421},[],[1423],{"type":702,"value":768},{"type":702,"value":821},1775735655417]