๐ด Arrow Functions
const names = ["Jeong", "Seung", "Ryong"];
// using normal function
const array = names.map(function(item) {
return item + " โ";
});
// using array function
const array = names.map(item => {
return item + " โ";
});
// using implicit return
// ๐ { }๋ฅผ ์ฌ์ฉํ๋ฉด ์ ๋จ.
const array = names.map(item => item + " โ");
๐ 'this' in Arrow Functions
โช this๋ฅผ ์ฌ์ฉํ์ฌ ์ค์ฝํ ๋ฒ์์ ํด๋นํ๋ ๊ฐ์ฒด๋ฅผ ์ป์ด์ฌ ๋๋ Arrow function์ ์ฌ์ฉํ๋ฉด ์ ๋๋ค.
const button = document.querySelector("button");
// using normal function
button.addEventListener("click", function() {
console.log(this); // <button></button>
});
// using arrow function
button.addEventListener("click", () => {
console.log(this); // === console.log(window);
});
// using normal function
const ryong = {
name: "Ryong",
age: 28,
addYear() {
this.age++;
}
};
console.log(ryong.age); // 28
ryong.addYear();
ryong.addYear();
console.log(ryong.age); // 30
// using arrow function
const ryong = {
name: "Ryong",
age: 28,
addYear: () => {
this.age++;
}
};
console.log(ryong.age); // 28
ryong.addYear();
ryong.addYear();
console.log(ryong.age); // 28
๐ก Arrow Functions in the Real World
์๋์ ์ ์ฉํ ์์ ๋ค์ ๊ณตํต์ ์ผ๋ก ์ ์ฉ๋ ๊ฐ์ฒด๋ฅผ ํ๋ ๋ง๋ค์ด๋ณด์.
const emails = [
"jeong@no.com",
"naver@google.com",
"seung@gmail.com",
"ryong@hello.com",
"ryong@gmail.com"
];
โช find ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์ฒซ ๋ฒ์งธ ์๋ฆฌ๋จผํธ ๊ฐ์ ๋ฐํํ๋ค.
const foundMail = emails.find(item => item.includes("@gmail.com"));
console.log(foundMail); // seung@gmail.com
โช filter ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์๋ฆฌ๋จผํธ๋ค๋ก ์๋ก์ด Array๋ฅผ ๋ง๋ค์ด์ ๋ฆฌํดํ๋ ํจ์์ด๋ค.
const noGmail = emails.filter(item => !item.includes("@gmail"));
console.log(noGmail); // [ 'jeong@no.com', 'naver@google.com', 'ryong@hello.com' ]
โช map ๊ฐ Array์ ์๋ฆฌ๋จผํธ๋ง๋ค ์ ๊ณต๋ ํจ์๋ฅผ ์์๋๋ก ์คํํ๋ ํจ์์ด๋ค.
const cleaned = emails.map(email => email.split("@")[0]);
console.log(cleaned); // ["jeong", "naver", "seung", "ryong", "ryong"]
// if you wanna return object
// {}์ ์ฌ์ฉํ๋ฉด implicit return์ ์ฌ์ฉํ์ง ๋ชปํ๋ฏ๋ก,
// object๋ฅผ returnํ๊ธฐ ์ํด์๋ ()๋ฅผ ์์ ์ฌ์ฉํด์ค๋ค.
const cleaned = emails.map((email, index) => ({
username: email.split("@")[0],
index
}));
console.table(cleaned);
/* (index) username index
0 "jeong" 0
1 "naver" 1
2 "seung" 2
3 "ryong" 3
4 "ryong" 4
*/
๐ข Default Values
const DEFAULT = "default";
const sayHi = (aName = DEFAULT) => "Hello " + aName;
console.log(sayHi()); // Hello default
'JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ JS ] Rest And Spread (0) | 2022.07.05 |
---|---|
[ JS ] Destructuring (0) | 2022.07.05 |
[ JS ] Array (0) | 2022.07.05 |
[ JS ] Strings (0) | 2022.07.05 |
[ JS ] Variables and Operator (0) | 2022.07.05 |