[JS] ES6 - Array

[JS] ES6 - Array

이채현

Array

Array.of()

무엇이든 Array로 만들어준다.

1
2
3
4
// Array.of()
const alphabet = ["a", "b", "c", "d"];
const alphabet = Array.of("a", "b", "c", "d")const alphabet = Array.of("a", "b", "c", "d", 1, 2, 3);;
console.log(alphabet);

Array.from()

Array.from(array같이 생긴 것)

😠 querySelectorgetElementbyClassName으로 엘리먼트 찾으면 array 같지만 아닌 다른 저장 포맷으로 저장된다

array-like object를 array로 바꿔준다.

1
2
3
4
5
6
7
8
9
10
11
const buttons = document.getElementsByClassName("btn");
console.log(buttons);
// buttons는 Array가 아니기 때문에
// 아래와 같이 forEach를 사용할 수 없다.
buttons.forEach((button) => {
button.addEventListener("click", () => console.log("I ve been clickeds"));
});
----------------
Array.from(buttons).forEach((button) => {
button.addEventListener("click", () => console.log("I ve been clickeds"));
});

Array.find()

Array.prototype.find() - JavaScript | MDN

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Array.find()
*/
const friends = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
];

const target1 = friends.find((friend) => friend.includes("@yahoo.com"));
// 조건을 넣어주면 forEach를 돌리면서 그에 맞는 값을 리턴해준다
// 찾은 첫번째 값만 반환해준다
// 없으면 undefined반환한다
console.log(target1);

Array.findIndex()

Array.prototype.findIndex() - JavaScript | MDN

1
2
3
4
5
6
7
8
9
10
/**
* Array.findIndex()
*/
const target2 = friends.findIndex((friend) => friend.includes("@yahoo.com"));
// 인덱스가 필요할때!
// 없으면 -1반환한다
console.log(target2);
const userName = friends[target2].split("@")[0];
const email = "yahoo.com";
console.log(`${userName}@${email}`);

Array.fill()

Array.prototype.fill() - JavaScript | MDN

1
2
3
4
5
if (target2 !== -1) {
friends.fill("*".repeat(5), target2 + 1);
// target부터 모든 변수는 다 채울값으로 채워줌
}
console.log(friends);
[JS] ES6 - Strings

[JS] ES6 - Strings

이채현

Strings

Template Literal

variable을 가진 문자열을 쓰는 방법에 대한 개선

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const sayHi = (aName = "anon") => {
return "Hello " + aName;
};

==>
/**
* 변수
*/
const sayHi = (aName = "anon") => {
return `Hello ${aName}`;
}
/**
* 함수
*/
const add = (a, b) => a + b;
console.log(`hello how are you ${add(6, 6)}`);

HTML Fragments 1

1
2
3
4
5
6
7
8
9
10
11
const wrapper = document.querySelector(".wrapper");

const addWelcome = () => {
const div = document.createElement("div");
const h1 = document.createElement("h1");
h1.innerText = "Hello";
div.append(h1);
wrapper.append(div);
};

setTimeout(addWelcome, 1000);

1
2
3
4
5
6
7
8
const addWelcome = () => {
const div = `
<div class="hello">
<h1>Hello</h1>
</div>
`;
wrapper.innerHTML = div;
};
  • template literal은 ``` … space를 고려한다.

HTML Fragments 2

1
2
3
4
5
6
7
8
9
10
const alphas = ["A", "B", "C", "D"];

const ul = document.createElement("ul");
const list = `
<h1>Alphabet</h1>
<ul>
${alphas.map(alpha => `<li>${alpha}</li>`).join("")}
</ul>
`;
wrapper.innerHTML = list;

Cloning Styled Components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Cloning Styled Components
*/

const styled = (aElement) => {
const el = document.createElement(aElement);
return (args) => {
const styles = args[0];
el.style = styles;
return el;
};
};

// 아래 코드는 함수를 두변 연속 호출 하는 꼴이기 때문에
// 위 함수에서 클로저로 함수를 또 한번 호출할 필요가 있다.
const title = styled("h1")`
background-color: red;
color: blue;
`;

const subTitle = styled("span")`
color: green;
`;

title.innerText = "We just cloned";
subTitle.innerText = "Styled Components";

document.body.append(title, subTitle);

More String Improvements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* includes()
*/
const isEmail = (email) => email.includes("@");
console.log(isEmail("[email protected]")); // true
console.log(isEmail("myEmail")); // false

/**
* repeat()
*/
const CC_NUMBER = "6060"; // ************6060로 보여주기
const displayName = `${"*".repeat(10)}${CC_NUMBER}`;
console.log(displayName); // **********6060

/**
* startsWith(), endsWith()
*/
const name = "Mr. abc";
console.log(name.startsWith("Mr")); // true
console.log(name.endsWith("abc")); // true
[JS] ES6 - Functions

[JS] ES6 - Functions

이채현

Functions

Arrow Functions

기존 함수의 모습을 개선했다.

기존 함수

1
2
3
4
5
6
7
8
9
10
11
function Hello() {
return "hi";
}
console.log(Hello());

const names = ["kim", "lee", "park"];

const hearts = names.map(function (name) {
return name + " ❤️";
});
console.log(hearts);

Arrow Functions(1) - base

1
2
3
4
5
6
7
8
9
10
11
const Hello = () => {
return "hi";
};
console.log(Hello());

const names = ["kim", "lee", "park"];

const hearts = names.map((name) => {
return name + " ❤️";
});
console.log(hearts);

Arrow Functions(2) - implicit return

1
2
3
4
5
6
7
const Hello = () => "hi";
console.log(Hello());

const names = ["kim", "lee", "park"];

const hearts = names.map(name => name + " ❤️");
console.log(hearts);

this in Arrow Functions (Event listener in arrow function)

일반 콜백 함수안에서 this는 이벤트리스너에 연결 된 엘리먼트를 가리킨다. 하지만, arrow function안에서 this는 window를 가리킨다.

결론, this를 함수 안에 익명함수로 사용할 때는 Arrow Function이 아닌 일반 표준 funtion 형태로 사용해야한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const thisTest = {
cnt: 0,
addCnt() {
this.cnt++;
},
addCnt2: () => {
this.cnt++;
},
};
console.log(thisTest.cnt); // 0
thisTest.addCnt();
console.log(thisTest.cnt); // 1
thisTest.addCnt2;
console.log(thisTest.cnt); // 1

Default Values

1
2
3
4
5
6
const sayHi = (aName = "anon") => {
return `Hello ${aName}`;
}

console.log(sayHi());
console.log(sayHi('chaehyeon'));
[JS] ES6 - Variables

[JS] ES6 - Variables

이채현

Variables

Let and Const

var를 절대 사용하지 않고 let & const 사용하기

  • var를 쓰면 안되는 이유

    • var hoisting
      

      때문에…

      • var는 라이프사이클에서… 선언과 초기화를 동시에 한다.
      • global scope에 변수/함수를 선언할 경우 아무리 아래에 선언해도 제일 위로 올라간다. → 어디서 선언했든 상관없이, 항상 제일 위로 선언을 끌어올려준다.
      • block scope를 철저히 무시한다.

    ⇒ 이러한 유연성으로 작은 어플리케이션을 금방 만들 수 있지만, 프로젝트의 규모가 커지면서 나중에서는 선언하지도 않은 값이 멋대로 출력되거나, 개발자들간의 협업에서 여러가지 문제점이 생길 수 있다.

  • let은 선언과 초기화가 분리되어 그 사이에 TDZ가 생성되고, 접근할 경우 Reference Error가 발생한다.

  • const는 선언과 초기화가 동시에 진행되지만, 선언 이전에 TDZ가 생성되어 접근하면 Reference Error가 발생한다.

    Dead Zone

    temporal dead zone(TDZ)에 영향을 받는 구문은 크게..

    • const 변수
    • let 변수
    • class 구문
    • constructor() 내부의 super()
    • 기본 함수 매개변수

Block Scope

let & const는 block scope {}를 가짐

  • 외부에서 접근 불가능하다.

var는 function scope를 가짐

  • function 안에서 생성 된 var변수는 외부 function에서 접근 할 수 없지만, if/else, for등안에서 생성 된 var는 어디서는 접근 가능하다.

Immutabe Data Types

primitive types, frozen objects … 값이 바뀌지 않은 type

CONSTANTS는 Immutable Data Types이며, 프로그래밍할 때 왠만하면 Immutable Data Types를 사용하자.

💁🏻‍♀️ Immutable Data Types을 사용해야 하는 이유

  • security 해커들이 코드의 값을 바꾸는 것을 방지한다.
  • thread safety 어플리케이션을 실행하면 한가지의 프로세스가 할당되고, 그 프로세스 안에서 다양한 thread가 동시에 돌아가게 된다.이때 이 다양한 thread가 동시에 변수에 접근해서 값을 변경할 수 있게 되는 위험성이 생기는데, 이것을 방지한다.
  • reduce human mistakes 앞으로 해당 코드를 변경할 더 좋은 방안이 없다면, const 를 이용해 작성하여 본인 혹은 다른 개발자가 코드를 변경할때 발생할 수 있는 실수를 방지해준다.