diff --git a/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/solution.md b/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/solution.md index cc226e7c5..5182475f2 100644 --- a/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/solution.md +++ b/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/solution.md @@ -1,13 +1,13 @@ ```js run let user = { - name: "John", + name: "Іван", years: 30 }; let {name, years: age, isAdmin = false} = user; -alert( name ); // John +alert( name ); // Іван alert( age ); // 30 alert( isAdmin ); // false ``` \ No newline at end of file diff --git a/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/task.md b/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/task.md index b68db5c59..f4d9741e1 100644 --- a/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/task.md +++ b/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/task.md @@ -2,32 +2,32 @@ importance: 5 --- -# Destructuring assignment +# Деструктуроване присвоєння -We have an object: +У нас є об’єкт: ```js let user = { - name: "John", + name: "Іван", years: 30 }; ``` -Write the destructuring assignment that reads: +Напишіть деструктуроване присвоєння, яке зчитує: -- `name` property into the variable `name`. -- `years` property into the variable `age`. -- `isAdmin` property into the variable `isAdmin` (false, if no such property) +- властивість `name` у змінну `name`. +- властивість `years` у змінну `age`. +- властивість `isAdmin` у змінну `isAdmin` (false, якщо така властивість відсутня) -Here's an example of the values after your assignment: +Ось приклад значень після вашого присвоєння: ```js -let user = { name: "John", years: 30 }; +let user = { name: "Іван", years: 30 }; -// your code to the left side: +// ваш код зліва: // ... = user -alert( name ); // John +alert( name ); // Іван alert( age ); // 30 alert( isAdmin ); // false ``` diff --git a/1-js/05-data-types/10-destructuring-assignment/6-max-salary/task.md b/1-js/05-data-types/10-destructuring-assignment/6-max-salary/task.md index 9f33de089..23adc8601 100644 --- a/1-js/05-data-types/10-destructuring-assignment/6-max-salary/task.md +++ b/1-js/05-data-types/10-destructuring-assignment/6-max-salary/task.md @@ -2,21 +2,21 @@ importance: 5 --- -# The maximal salary +# Максимальна зарплата -There is a `salaries` object: +Є об’єкт `salaries`: ```js let salaries = { - "John": 100, - "Pete": 300, - "Mary": 250 + "Іван": 100, + "Петро": 300, + "Марія": 250 }; ``` -Create the function `topSalary(salaries)` that returns the name of the top-paid person. +Створіть функцію `topSalary(salaries)` яка повертає ім’я найбільш високооплачуваної особи. -- If `salaries` is empty, it should return `null`. -- If there are multiple top-paid persons, return any of them. +- Якщо об’єкт `salaries` пустий, функція повинна повернути `null`. +- Якщо є кілька високооплачуваних осіб, поверніть будь-якого з них. -P.S. Use `Object.entries` and destructuring to iterate over key/value pairs. +P.S. Використовуйте `Object.entries` і деструктурування для перебору пар ключ/значення. diff --git a/1-js/05-data-types/10-destructuring-assignment/article.md b/1-js/05-data-types/10-destructuring-assignment/article.md index fb9346aa2..9da78372b 100644 --- a/1-js/05-data-types/10-destructuring-assignment/article.md +++ b/1-js/05-data-types/10-destructuring-assignment/article.md @@ -1,51 +1,51 @@ -# Destructuring assignment +# Деструктуроване присвоєння -The two most used data structures in JavaScript are `Object` and `Array`. +Двома найбільш вживаними структурами даних у JavaScript є `Object` та `Array`. -- Objects allow us to create a single entity that stores data items by key. -- Arrays allow us to gather data items into an ordered list. +- Об’єкти дозволяють нам створити єдину сутність, яка зберігатиме дані за ключем. +- Масиви дозволяють нам зібрати елементи даних у впорядкований список. -Although, when we pass those to a function, it may need not an object/array as a whole. It may need individual pieces. +Хоча, коли ми передаємо їх у функції, їй може знадобитися не об’єкт/масив в цілому, а тільки окремі їх елементи. -*Destructuring assignment* is a special syntax that allows us to "unpack" arrays or objects into a bunch of variables, as sometimes that's more convenient. +*Деструктуроване присвоєння* -- це спеціальний синтаксис, що дозволяє нам "розпаковувати" масиви чи об’єкти в купу змінних, оскільки іноді це зручніше. -Destructuring also works great with complex functions that have a lot of parameters, default values, and so on. Soon we'll see that. +Деструктурування також чудово працює зі складними функціями, які мають багато параметрів, типових значень тощо. Незабаром ми це побачимо. -## Array destructuring +## Деструктурування масиву -Here's an example of how an array is destructured into variables: +Ось приклад того, як масив деструктурується на змінні: ```js -// we have an array with the name and surname -let arr = ["John", "Smith"] +// у нас є масив з іменем та прізвищем +let arr = ["Іван", "Петренко"] *!* -// destructuring assignment -// sets firstName = arr[0] -// and surname = arr[1] +// деструктуроване присвоєння +// встановлює firstName = arr[0] +// та surname = arr[1] let [firstName, surname] = arr; */!* -alert(firstName); // John -alert(surname); // Smith +alert(firstName); // Іван +alert(surname); // Петренко ``` -Now we can work with variables instead of array members. +Тепер ми можемо працювати зі змінними замість елементів масиву. -It looks great when combined with `split` or other array-returning methods: +Це чудово виглядає в поєднанні зі `split` або іншими методами повернення масиву: ```js run -let [firstName, surname] = "John Smith".split(' '); -alert(firstName); // John -alert(surname); // Smith +let [firstName, surname] = "Іван Петренко".split(' '); +alert(firstName); // Іван +alert(surname); // Петренко ``` -As you can see, the syntax is simple. There are several peculiar details though. Let's see more examples, to better understand it. +Як бачите, синтаксис простий. Хоча є кілька особливих деталей. Давайте розглянемо більше прикладів, щоб краще це зрозуміти. -````smart header="\"Destructuring\" does not mean \"destructive\"." -It's called "destructuring assignment," because it "destructurizes" by copying items into variables. But the array itself is not modified. +````smart header="\"Деструктурування\" не означає \"руйнування\"." +Це називається "деструктуроване присвоєння", оскільки воно "деструктурує" шляхом копіювання елементів у змінні. Але сам масив не змінюється. -It's just a shorter way to write: +Це просто коротший спосіб написати: ```js // let [firstName, surname] = arr; let firstName = arr[0]; @@ -53,141 +53,141 @@ let surname = arr[1]; ``` ```` -````smart header="Ignore elements using commas" -Unwanted elements of the array can also be thrown away via an extra comma: +````smart header="Ігноруйте елементи за допомогою коми" +Небажані елементи масиву також можна викинути за допомогою додаткової коми: ```js run *!* -// second element is not needed -let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]; +// другий елемент не потрібен +let [firstName, , title] = ["Юлій", "Цезар", "Консул", "Римської республіки"]; */!* -alert( title ); // Consul +alert( title ); // Консул ``` -In the code above, the second element of the array is skipped, the third one is assigned to `title`, and the rest of the array items is also skipped (as there are no variables for them). +У наведеному вище коді другий елемент масиву пропускається, третій присвоюється `title`, а решта елементів масиву також пропускається (оскільки для них немає змінних). ```` -````smart header="Works with any iterable on the right-side" +````smart header="Працює з будь-якими типами даних, що перебираються у правій стороні" -...Actually, we can use it with any iterable, not only arrays: +...Насправді, ми можемо використовувати його з будь-якими даними, які перебираються, а не тільки з масивами: ```js let [a, b, c] = "abc"; // ["a", "b", "c"] let [one, two, three] = new Set([1, 2, 3]); ``` -That works, because internally a destructuring assignment works by iterating over the right value. It's kind of syntax sugar for calling `for..of` over the value to the right of `=` and assigning the values. +Це спрацьовує, оскільки зсередини деструктуроване присвоєння працює шляхом ітерації правого значення. Це свого роду синтаксичний цукор для виклику `for..of` над значенням праворуч від `=` та присвоєння значень. ```` -````smart header="Assign to anything at the left-side" -We can use any "assignables" at the left side. +````smart header="Присвоюйте до будь-чого зліва" +Ми можемо використовувати будь-яке "присвоюване" з лівої сторони. -For instance, an object property: +Наприклад, присвоїти властивості об’єкта: ```js run let user = {}; -[user.name, user.surname] = "John Smith".split(' '); +[user.name, user.surname] = "Іван Петренко".split(' '); -alert(user.name); // John -alert(user.surname); // Smith +alert(user.name); // Іван +alert(user.surname); // Петренко ``` ```` -````smart header="Looping with .entries()" -In the previous chapter we saw the [Object.entries(obj)](mdn:js/Object/entries) method. +````smart header="Цикл з .entries()" +У попередньому розділі ми бачили метод [Object.entries(obj)](mdn:js/Object/entries). -We can use it with destructuring to loop over keys-and-values of an object: +Ми можемо використовувати його з деструктуруванням для циклічного перебору ключів-та-значень об’єкта: ```js run let user = { - name: "John", + name: "Іван", age: 30 }; -// loop over keys-and-values +// перебрати циклом ключі-та-значення *!* for (let [key, value] of Object.entries(user)) { */!* - alert(`${key}:${value}`); // name:John, then age:30 + alert(`${key}:${value}`); // name:Іван, потім age:30 } ``` -The similar code for a `Map` is simpler, as it's iterable: +Подібний код для `Map` простіший, оскільки він є струтктурою даних, яка перебирається: ```js run let user = new Map(); -user.set("name", "John"); +user.set("name", "Іван"); user.set("age", "30"); *!* -// Map iterates as [key, value] pairs, very convenient for destructuring +// Map ітерує як пари [key, value], що дуже зручно для деструктурування for (let [key, value] of user) { */!* - alert(`${key}:${value}`); // name:John, then age:30 + alert(`${key}:${value}`); // name:Іван, then age:30 } ``` ```` -````smart header="Swap variables trick" -There's a well-known trick for swapping values of two variables using a destructuring assignment: +````smart header="Трюк обміну змінними" +Існує відомий трюк для обміну значень двох змінних за допомогою деструктурованого присвоєння: ```js run -let guest = "Jane"; -let admin = "Pete"; +let guest = "Джейн"; +let admin = "Пітер"; -// Let's swap the values: make guest=Pete, admin=Jane +// Давайте обміняємо значення: зробімо guest=Пітер, admin=Джейн *!* [guest, admin] = [admin, guest]; */!* -alert(`${guest} ${admin}`); // Pete Jane (successfully swapped!) +alert(`${guest} ${admin}`); // Пітер Джейн (успішно обмінялися!) ``` -Here we create a temporary array of two variables and immediately destructure it in swapped order. +Тут ми створюємо тимчасовий масив з двох змінних і негайно деструктуруємо його в порядку обміну. -We can swap more than two variables this way. +Таким методом ми можемо поміняти місцями більше двох змінних. ```` -### The rest '...' +### Залишкові параметри '...' -Usually, if the array is longer than the list at the left, the "extra" items are omitted. +Зазвичай, якщо масив довший від списку зліва, "зайві" елементи опускаються. -For example, here only two items are taken, and the rest is just ignored: +Наприклад, тут береться лише два елементи, а решта просто ігнорується: ```js run -let [name1, name2] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]; +let [name1, name2] = ["Юлій", "Цезар", "Консул", "Римської Республіки"]; -alert(name1); // Julius -alert(name2); // Caesar -// Further items aren't assigned anywhere +alert(name1); // Юлій +alert(name2); // Цезар +// Інші пункти ніде не присвоєні ``` -If we'd like also to gather all that follows -- we can add one more parameter that gets "the rest" using three dots `"..."`: +Якщо ми хочемо також зібрати все наступне -- ми можемо додати ще один параметр, який отримує "решту", використовуючи три крапки `"..."`: ```js run -let [name1, name2, *!*...rest*/!*] = ["Julius", "Caesar", *!*"Consul", "of the Roman Republic"*/!*]; +let [name1, name2, *!*...rest*/!*] = ["Юлій", "Цезар", *!*"Консул", "Римської Республіки"*/!*]; *!* -// rest is array of items, starting from the 3rd one -alert(rest[0]); // Consul -alert(rest[1]); // of the Roman Republic +// rest -- це масив елементів, починаючи з 3-го +alert(rest[0]); // Консул +alert(rest[1]); // Римської Республіки alert(rest.length); // 2 */!* ``` -The value of `rest` is the array of the remaining array elements. +Значенням `rest` є масив з решти елементів масиву. -We can use any other variable name in place of `rest`, just make sure it has three dots before it and goes last in the destructuring assignment. +Ми можемо використовувати будь-яку іншу назву змінної замість `rest`, просто переконайтесь, що перед нею є три точки і вона залишається останньою у деструктурованому присвоєнні. ```js run -let [name1, name2, *!*...titles*/!*] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]; -// now titles = ["Consul", "of the Roman Republic"] +let [name1, name2, *!*...titles*/!*] = ["Юлій", "Цезар", "Консул", "Римської Республіки"]; +// тепер titles = ["Консул", "Римської Республіки"] ``` -### Default values +### Типові значення -If the array is shorter than the list of variables at the left, there'll be no errors. Absent values are considered undefined: +Якщо масив коротший за список змінних зліва, помилок не буде. Відсутні значення вважаються невизначеними: ```js run *!* @@ -198,49 +198,49 @@ alert(firstName); // undefined alert(surname); // undefined ``` -If we want a "default" value to replace the missing one, we can provide it using `=`: +Якщо ми хочемо, щоб "типове" значення замінило б відсутнє, ми можемо надати його за допомогою `=`: ```js run *!* -// default values -let [name = "Guest", surname = "Anonymous"] = ["Julius"]; +// типове значення +let [name = "Гість", surname = "Анонім"] = ["Юлій"]; */!* -alert(name); // Julius (from array) -alert(surname); // Anonymous (default used) +alert(name); // Юлій (з масиву) +alert(surname); // Анонім (використовується типове значення) ``` -Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided. +Початкові значення можуть бути більш складними виразами або навіть викликами функцій. Вони визначаються, лише якщо значення не надано. -For instance, here we use the `prompt` function for two defaults: +Наприклад, тут ми використовуємо функцію `prompt` для двох типових значень: ```js run -// runs only prompt for surname -let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"]; +// запускає prompt тільки для surname +let [name = prompt("Ім'я?"), surname = prompt('Прізвище?')] = ["Юлій"]; -alert(name); // Julius (from array) -alert(surname); // whatever prompt gets +alert(name); // Юлій (визначено з масиву) +alert(surname); // значення, отримане з prompt ``` -Please note: the `prompt` will run only for the missing value (`surname`). +Зверніть увагу: `prompt` буде спрацьовувати лише для відсутнього значення (`surname`). -## Object destructuring +## Деструктурування об’єктів -The destructuring assignment also works with objects. +Деструктуроване присвоєння також працює з об’єктами. -The basic syntax is: +Основний синтаксис такий: ```js let {var1, var2} = {var1:…, var2:…} ``` -We should have an existing object at the right side, that we want to split into variables. The left side contains an object-like "pattern" for corresponding properties. In the simplest case, that's a list of variable names in `{...}`. +Ми повинні мати існуючий об’єкт праворуч, який ми хочемо розділити на змінні. Ліва частина містить об’єктоподібний "шаблон" для відповідних властивостей. У найпростішому випадку це список імен змінних у `{...}`. -For instance: +Наприклад: ```js run let options = { - title: "Menu", + title: "Меню", width: 100, height: 200 }; @@ -249,27 +249,27 @@ let options = { let {title, width, height} = options; */!* -alert(title); // Menu +alert(title); // Меню alert(width); // 100 alert(height); // 200 ``` -Properties `options.title`, `options.width` and `options.height` are assigned to the corresponding variables. +Властивості `options.title`, `options.width` та `options.height` призначені відповідним змінним. -The order does not matter. This works too: +Порядок не має значення. Це теж працює: ```js -// changed the order in let {...} -let {height, width, title} = { title: "Menu", height: 200, width: 100 } +// змінили порядок у let {...} +let {height, width, title} = { title: "Меню", height: 200, width: 100 } ``` -The pattern on the left side may be more complex and specify the mapping between properties and variables. +Шаблон з лівого боку може бути більш складним і визначати зіставлення властивостей та змінних. -If we want to assign a property to a variable with another name, for instance, make `options.width` go into the variable named `w`, then we can set the variable name using a colon: +Якщо ми хочемо присвоїти властивість змінній з іншим іменем, наприклад, зробити так, щоб `options.width` переходив до змінної з назвою `w`, то ми можемо встановити ім’я змінної за допомогою двокрапки: ```js run let options = { - title: "Menu", + title: "Меню", width: 100, height: 200 }; @@ -283,144 +283,144 @@ let {width: w, height: h, title} = options; // height -> h // title -> title -alert(title); // Menu +alert(title); // Меню alert(w); // 100 alert(h); // 200 ``` -The colon shows "what : goes where". In the example above the property `width` goes to `w`, property `height` goes to `h`, and `title` is assigned to the same name. +Двокрапка показує "що: куди йде". У наведеному вище прикладі властивість `width` переходить у `w`, властивість `height` переходить у `h`, а `title` присвоюється тому самому імені. -For potentially missing properties we can set default values using `"="`, like this: +Для потенційно відсутніх властивостей ми можемо встановити типові значення за допомогою `"="`, наприклад: ```js run let options = { - title: "Menu" + title: "Меню" }; *!* let {width = 100, height = 200, title} = options; */!* -alert(title); // Menu +alert(title); // Меню alert(width); // 100 alert(height); // 200 ``` -Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided. +Так само, як і з масивами або параметрами функцій, типові значення можуть бути будь-якими виразами або навіть викликами функцій. Вони будуть оцінені, якщо значення не надано. -In the code below `prompt` asks for `width`, but not for `title`: +У коді нижче `prompt` запитує `width`, але не `title`: ```js run let options = { - title: "Menu" + title: "Меню" }; *!* -let {width = prompt("width?"), title = prompt("title?")} = options; +let {width = prompt("Ширина?"), title = prompt("Заголовок?")} = options; */!* -alert(title); // Menu -alert(width); // (whatever the result of prompt is) +alert(title); // Меню +alert(width); // (будь-який результат з prompt) ``` -We also can combine both the colon and equality: +Ми також можемо поєднати двокрапку та рівність: ```js run let options = { - title: "Menu" + title: "Меню" }; *!* let {width: w = 100, height: h = 200, title} = options; */!* -alert(title); // Menu +alert(title); // Меню alert(w); // 100 alert(h); // 200 ``` -If we have a complex object with many properties, we can extract only what we need: +Якщо у нас є складний об’єкт з багатьма властивостями, ми можемо витягти лише те, що нам потрібно: ```js run let options = { - title: "Menu", + title: "Меню", width: 100, height: 200 }; -// only extract title as a variable +// вибирає тільки title як змінну let { title } = options; -alert(title); // Menu +alert(title); // Меню ``` -### The rest pattern "..." +### Залишок об’єкту "..." -What if the object has more properties than we have variables? Can we take some and then assign the "rest" somewhere? +Що робити, якщо об’єкт має більше властивостей, ніж ми маємо змінних? Чи можемо ми взяти частину, а потім призначити кудись «залишок»? -We can use the rest pattern, just like we did with arrays. It's not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones. +Ми можемо використовувати шаблон залишкового оператору, так само, як ми робили з масивами. Він не підтримується деякими старішими браузерами (IE, використовуйте Babel для поліфілу), але працює в сучасних. -It looks like this: +Це виглядає наступним чином: ```js run let options = { - title: "Menu", + title: "Меню", height: 200, width: 100 }; *!* -// title = property named title -// rest = object with the rest of properties +// title = властивість з назвою title +// rest = об’єкт з залишковими властивостями let {title, ...rest} = options; */!* -// now title="Menu", rest={height: 200, width: 100} +// тепер title="Меню", rest={height: 200, width: 100} alert(rest.height); // 200 alert(rest.width); // 100 ``` -````smart header="Gotcha if there's no `let`" -In the examples above variables were declared right in the assignment: `let {…} = {…}`. Of course, we could use existing variables too, without `let`. But there's a catch. +````smart header="Зверніть увагу, якщо `let` відсутній" +У наведених вище прикладах змінні були оголошені прямо в присвоєнні: `let {…} = {…}`. Звичайно, ми також можемо використовувати існуючі змінні без `let`. Але тут може бути підступ. -This won't work: +Це не спрацює: ```js run let title, width, height; -// error in this line -{title, width, height} = {title: "Menu", width: 200, height: 100}; +// помилка в цьому рядку +{title, width, height} = {title: "Меню", width: 200, height: 100}; ``` -The problem is that JavaScript treats `{...}` in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this: +Проблема в тому, що JavaScript розглядає `{...}` в основному потоці коду (а не всередині іншого виразу) як блок коду. Такі блоки коду можна використовувати для групування операторів, наприклад: ```js run { - // a code block - let message = "Hello"; + // блок коду + let message = "Привіт"; // ... alert( message ); } ``` -So here JavaScript assumes that we have a code block, that's why there's an error. We want destructuring instead. +Отже, тут JavaScript припускає, що у нас є блок коду, тому і виникає помилка. Натомість ми хочемо деструктурування. -To show JavaScript that it's not a code block, we can wrap the expression in parentheses `(...)`: +Щоб показати JavaScript, що це не блок коду, ми можемо загорнути вираз у дужки `(...)`: ```js run let title, width, height; -// okay now +// тепер працює *!*(*/!*{title, width, height} = {title: "Menu", width: 200, height: 100}*!*)*/!*; -alert( title ); // Menu +alert( title ); // Меню ``` ```` -## Nested destructuring +## Вкладене деструктурування -If an object or an array contain other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions. +Якщо об’єкт або масив містять інші вкладені об’єкти та масиви, ми можемо використовувати більш складні шаблони з лівого боку для вилучення більш глибоких частин. -In the code below `options` has another object in the property `size` and an array in the property `items`. The pattern at the left side of the assignment has the same structure to extract values from them: +У наведеному нижче коді `options` містить інший об'єкт у властивості `size` та масив у властивості `items`. Шаблон у лівій частині присвоєння має ту саму структуру для вилучення з них значень: ```js run let options = { @@ -428,40 +428,40 @@ let options = { width: 100, height: 200 }, - items: ["Cake", "Donut"], + items: ["Торт", "Пончик"], extra: true }; -// destructuring assignment split in multiple lines for clarity +// деструктурування розподілене на кілька рядків для наочності let { - size: { // put size here + size: { // помістимо тут size width, height }, - items: [item1, item2], // assign items here - title = "Menu" // not present in the object (default value is used) + items: [item1, item2], // тут призначимо items + title = "Меню" // немає в об’єкті (використовується типове значення) } = options; -alert(title); // Menu +alert(title); // Меню alert(width); // 100 alert(height); // 200 -alert(item1); // Cake -alert(item2); // Donut +alert(item1); // Торт +alert(item2); // Пончик ``` -All properties of `options` object except `extra` that is absent in the left part, are assigned to corresponding variables: +Усі властивості об’єкта `options`, окрім `extra`, яке відсутнє у лівій частині, призначаються відповідним змінним:  -Finally, we have `width`, `height`, `item1`, `item2` and `title` from the default value. +Нарешті, ми маємо `width`, `height`, `item1`, `item2` та `title` з типовим значенням. -Note that there are no variables for `size` and `items`, as we take their content instead. +Зауважте, що для `size` та `items` немає змінних, оскільки ми беремо їх вміст. -## Smart function parameters +## Розумні параметри функції -There are times when a function has many parameters, most of which are optional. That's especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, items list and so on. +Бувають випадки, коли функція має багато параметрів, більшість з яких є необов’язковими. Особливо це стосується користувацьких інтерфейсів. Уявіть собі функцію, яка створює меню. Вона може мати ширину, висоту, назву, список елементів тощо. -Here's a bad way to write such function: +Нижче наведено поганий спосіб написати таку функцію: ```js function showMenu(title = "Untitled", width = 200, height = 100, items = []) { @@ -469,32 +469,32 @@ function showMenu(title = "Untitled", width = 200, height = 100, items = []) { } ``` -In real-life, the problem is how to remember the order of arguments. Usually IDEs try to help us, especially if the code is well-documented, but still... Another problem is how to call a function when most parameters are ok by default. +У реальному житті проблема полягає в тому, як запам’ятати порядок аргументів. Зазвичай IDE намагаються нам допомогти, особливо якщо код добре задокументований, але все ж... Інша проблема полягає в тому, як викликати функцію, коли більшість параметрів типово в порядку. -Like this? +Можливо так? ```js -// undefined where default values are fine +// undefined де підходять типові значення showMenu("My Menu", undefined, undefined, ["Item1", "Item2"]) ``` -That's ugly. And becomes unreadable when we deal with more parameters. +Це негарно. І стає нечитабельним, коли ми маємо справу з більшою кількістю параметрів. -Destructuring comes to the rescue! +На допомогу приходить деструктурування! -We can pass parameters as an object, and the function immediately destructurizes them into variables: +Ми можемо передати параметри як об’єкт, і функція негайно деструктурує їх на змінні: ```js run -// we pass object to function +// ми передаємо об’єкт до функції let options = { title: "My menu", items: ["Item1", "Item2"] }; -// ...and it immediately expands it to variables +// ...і вона негайно розгортає його до змінних function showMenu(*!*{title = "Untitled", width = 200, height = 100, items = []}*/!*) { - // title, items – taken from options, - // width, height – defaults used + // title, items – взяті з options, + // width, height – використовуються типові значення alert( `${title} ${width} ${height}` ); // My Menu 200 100 alert( items ); // Item1, Item2 } @@ -502,7 +502,7 @@ function showMenu(*!*{title = "Untitled", width = 200, height = 100, items = []} showMenu(options); ``` -We can also use more complex destructuring with nested objects and colon mappings: +Ми також можемо використовувати більш складне деструктурування з вкладеними об’єктами та двокрапками: ```js run let options = { @@ -513,9 +513,9 @@ let options = { *!* function showMenu({ title = "Untitled", - width: w = 100, // width goes to w - height: h = 200, // height goes to h - items: [item1, item2] // items first element goes to item1, second to item2 + width: w = 100, // width стає w + height: h = 200, // height стає h + items: [item1, item2] // перший елемент items йде до item1, другий - до item2 }) { */!* alert( `${title} ${w} ${h}` ); // My Menu 100 200 @@ -526,7 +526,7 @@ function showMenu({ showMenu(options); ``` -The full syntax is the same as for a destructuring assignment: +Повний синтаксис такий самий, як і для деструктурованого присвоєння: ```js function({ incomingProperty: varName = defaultValue @@ -534,17 +534,17 @@ function({ }) ``` -Then, for an object of parameters, there will be a variable `varName` for property `incomingProperty`, with `defaultValue` by default. +Тоді для об’єкта параметрів буде змінна `varName` для властивості `incomingProperty` з типовим значенням `defaultValue`. -Please note that such destructuring assumes that `showMenu()` does have an argument. If we want all values by default, then we should specify an empty object: +Зверніть увагу, що таке деструктурування передбачає, що `showMenu()` має аргумент. Якщо ми хочемо, щоб усі значення були типовими, ми повинні вказати порожній об’єкт: ```js -showMenu({}); // ok, all values are default +showMenu({}); // так добре, усі значення типові -showMenu(); // this would give an error +showMenu(); // це дасть помилку ``` -We can fix this by making `{}` the default value for the whole object of parameters: +Ми можемо виправити це, зробивши `{}` типовим значенням для всього об’єкта параметрів: ```js run function showMenu({ title = "Menu", width = 100, height = 200 }*!* = {}*/!*) { @@ -554,26 +554,26 @@ function showMenu({ title = "Menu", width = 100, height = 200 }*!* = {}*/!*) { showMenu(); // Menu 100 200 ``` -In the code above, the whole arguments object is `{}` by default, so there's always something to destructurize. +У наведеному вище коді весь об’єкт аргументів є типовим значенням `{}`, тому завжди є що деструктурувати. -## Summary +## Підсумки -- Destructuring assignment allows for instantly mapping an object or array onto many variables. -- The full object syntax: +- Деструктуруване присвоєння дозволяє миттєво зіставити об’єкт або масив з багатьма змінними. +- Повний синтаксис для об’єкта: ```js let {prop : varName = default, ...rest} = object ``` - This means that property `prop` should go into the variable `varName` and, if no such property exists, then the `default` value should be used. + Це означає, що властивість `prop` має входити до змінної `varName` і, якщо такої властивості не існує, слід використовувати `типове значення`. - Object properties that have no mapping are copied to the `rest` object. + Властивості об’єкта, які не мають зіставлення, копіюються в об’єкт `rest`. -- The full array syntax: +- Повний синтаксис для масиву: ```js let [item1 = default, item2, ...rest] = array ``` - The first item goes to `item1`; the second goes into `item2`, all the rest makes the array `rest`. + Перший елемент переходить до `item1`; другий переходить до `item2`, усі інші утворюють масив `rest`. -- It's possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one. +- Можна витягувати дані з вкладених масивів/об’єктів, для цього ліва сторона повинна мати ту ж структуру, що й права.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: