PROG_WAY_BLOG Telegram 93
Деструктуризация JavaScript

Как вы справляетесь с ситуацией, когда из объекта нужно сохранить определенную переменную?
Самым удобным способом является деструктуризация. Это синтаксис, когда мы в одну строку создаем несколько переменных из какого-либо объекта.


const json = {
name: "Denis",
surname: "Putnov",
age: 19,
email: "[email protected]",
adress: {
city: "Voronezh",
country: "Russia",
},
username: "grnbows"
}

Допустим, у нас есть такой json, пришедший нам с сервера. Реализуем функцию приветствия:

const sayHi = (person) =>
console.log(`Hi ${person.name} from ${person.adress.country}`)


Работает отменно и выводит нужное сообщение. Но код выглядит не очень красиво.

Перепишем функцию и воспользуемся деструктуризацией:

const sayHi = (person) => {
const {name, adress: {country}} = person

console.log(`Hi ${name} from ${country}`)
}


Функциональность та же, но отслеживать переменные проще и читаемость немного выше.
Но для идеала перенесем деструктуризацию в объявление входных параметров функции:

const sayHi = ({ name, adress: { country } }) =>
console.log(`Hi ${name} from ${country}`)


Таким образом внутри тела функции мы получаем доступ только к нужным переменным, повышаем читаемость кода.

На этом у меня всё. Спасибо за прочтение.

#javascript



tgoop.com/prog_way_blog/93
Create:
Last Update:

Деструктуризация JavaScript

Как вы справляетесь с ситуацией, когда из объекта нужно сохранить определенную переменную?
Самым удобным способом является деструктуризация. Это синтаксис, когда мы в одну строку создаем несколько переменных из какого-либо объекта.


const json = {
name: "Denis",
surname: "Putnov",
age: 19,
email: "[email protected]",
adress: {
city: "Voronezh",
country: "Russia",
},
username: "grnbows"
}

Допустим, у нас есть такой json, пришедший нам с сервера. Реализуем функцию приветствия:

const sayHi = (person) =>
console.log(`Hi ${person.name} from ${person.adress.country}`)


Работает отменно и выводит нужное сообщение. Но код выглядит не очень красиво.

Перепишем функцию и воспользуемся деструктуризацией:

const sayHi = (person) => {
const {name, adress: {country}} = person

console.log(`Hi ${name} from ${country}`)
}


Функциональность та же, но отслеживать переменные проще и читаемость немного выше.
Но для идеала перенесем деструктуризацию в объявление входных параметров функции:

const sayHi = ({ name, adress: { country } }) =>
console.log(`Hi ${name} from ${country}`)


Таким образом внутри тела функции мы получаем доступ только к нужным переменным, повышаем читаемость кода.

На этом у меня всё. Спасибо за прочтение.

#javascript

BY progway — программирование, IT




Share with your friend now:
tgoop.com/prog_way_blog/93

View MORE
Open in Telegram


Telegram News

Date: |

Add the logo from your device. Adjust the visible area of your image. Congratulations! Now your Telegram channel has a face Click “Save”.! Other crimes that the SUCK Channel incited under Ng’s watch included using corrosive chemicals to make explosives and causing grievous bodily harm with intent. The court also found Ng responsible for calling on people to assist protesters who clashed violently with police at several universities in November 2019. Although some crypto traders have moved toward screaming as a coping mechanism, several mental health experts call this therapy a pseudoscience. The crypto community finds its way to engage in one or the other way and share its feelings with other fellow members. Telegram message that reads: "Bear Market Screaming Therapy Group. You are only allowed to send screaming voice notes. Everything else = BAN. Text pics, videos, stickers, gif = BAN. Anything other than screaming = BAN. You think you are smart = BAN. While some crypto traders move toward screaming as a coping mechanism, many mental health experts have argued that “scream therapy” is pseudoscience. Scientific research or no, it obviously feels good.
from us


Telegram progway — программирование, IT
FROM American