조건부 연산자
삼항 연산자는 세 개의 피연산자를 가지는 연산자. if 문과 같은 원리로 조건에 따른 값을 결정할 때 사용
1
2
3
4
5
6
const cutOff = 80;
const passChecker = (score) =>
score > cutOff ? "합격입니다!" : "불합격입니다!";
console.log(passChecker(75));
if문 보다 간결하게 표현할 수 있지만, 내부에 함수나 변수를 선언하거나 표현식이 아닌 문장은 작성할 수 없다.
Spread 구문
여러 개의 값을 가지고 있는 배열이나 객체와 같은 값은 앞에 …을 붙여서 펼칠 수 있다.
1
2
3
4
5
6
7
8
9
10
11
const webPublishing = ["HTML", "CSS"];
const interactiveWeb = [...webPublishing, "JavaScript"];
console.log(webPublishing);
console.log(interactiveWeb);
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
이런 Spread 구문은 배열이나 객체를 복사하거나 복사 후 새로운 값을 추가할 때 사용한다. 또한 배열은 객체로 펼칠 수 있으나, 객체는 배열로 펼칠 수 없다.
1
2
3
4
5
6
7
8
9
10
const members = ["태호", "종훈", "우재"];
const newObject = { ...members };
console.log(newObject); // {0: "태호", 1: "종훈", 2: "우재"}
const topic = {
name: "모던 자바스크립트",
language: "JavaScript"
};
const newArray = [...topic]; // TypeError!
모던한 프로퍼티 표기법
변수나 함수를 사용해서 프로퍼티를 만들 때 프로퍼티 네임과 변수, 함수의 이름이 같으면 축약해서 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function sayHi() {
console.log("Hi!");
}
const title = "codeit";
const birth = 2017;
const job = "프로그래밍 강사";
const user = {
title,
birth,
job,
sayHi
};
console.log(user); // {title: "codeit", birth: 2017, job: "프로그래밍 강사", sayHi: ƒ}
메소드를 작성할 때도 function 키워드를 생략할 수 있다.
1
2
3
4
5
6
7
8
9
const user = {
firstName: "Tess",
lastName: "Jang",
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(user.getFullName()); // Tess Jang
또한 대괄호를 사용하면 다양한 표현식으로 프로퍼티 네임을 작성할 수 있다.
1
2
3
4
5
6
7
8
9
10
const propertyName = "birth";
const getJob = () => "job";
const codeit = {
["topic" + "name"]: "Modern JavaScript",
[propertyName]: 2017,
[getJob()]: "프로그래밍 강사"
};
console.log(codeit);
구조 분해
배열과 객체와 같이 여러 값을 가지고 있는 데이터 타입을 다룰 때 구조 분해 (Destructuring) 문법을 사용하면, 배열의 요소나 객체의 프로퍼티 값을 개별적인 변수에 따로 할당해서 다룰 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Array Destructuring
const members = ["코딩하는효준", "글쓰는유나", "편집하는민환"];
const [macbook, ipad, coupon] = members;
console.log(macbook); // 코딩하는효준
console.log(ipad); // 글쓰는유나
console.log(coupon); // 편집하는민환
// Object Destructuring
const macbookPro = {
title: "맥북 프로 16형",
price: 3690000
};
const { title, price } = macbookPro;
console.log(title); // 맥북 프로 16형
console.log(price); // 3690000
구조분해 문법을 사용할 때도 기본값 (Default)과 rest 문법을 사용할 수 있다.
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
29
// Array Destructuring
const members = [
"코딩하는효준",
"글쓰는유나",
undefined,
"편집하는민환",
"촬영하는재하"
];
const [macbook, ipad, airpod = "녹음하는규식", ...coupon] = members;
console.log(macbook); // 코딩하는효준
console.log(ipad); // 글쓰는유나
console.log(airpod); // 녹음하는규식
console.log(coupon); // (2) ["편집하는민환", "촬영하는재하"]
// Object Destructuring
const macbookPro = {
title: "맥북 프로 16형",
price: 3690000,
memory: "16 GB 2667 MHz DDR4",
storage: "1TB SSD 저장 장치"
};
const { title, price, color = "silver", ...rest } = macbookPro;
console.log(title); // 맥북 프로 16형
console.log(price); // 3690000
console.log(color); // silver
console.log(rest); // {memory: "16 GB 2667 MHz DDR4", storage: "1TB SSD 저장 장치"}
에러와 에러 객체
자바스크립트에서는 에러 발생 시 프로그램이 멈추고 이후의 코드는 동작하지 않는다. 또한 에러 발생 시 에러 객체가 만들어지는데, name, message 프로퍼티를 가지고 있다. 에러 객체는 직접 만들어 사용할 수 있는데,
1
throw new TypeError("타입 에러가 발생했습니다.");
try…catch 문
1
2
3
4
5
try {
// 실행할 코드
} catch (error) {
// 에러 발생 시 동작할 코드
}
try 문 안에 실행할 코드, try 문 안에 에러 발샐 시 동작할 코드를 작성한다. 이때 try문에서 에러가 발생하면 catch문이 실행되고, try문에서 에러가 발생하지 않으면 catch문의 코드는 동작하지 않는다. 마지막으로 try…catch문과 상관없이 항상 동작해야하는 코드가 있으면 finally문을 사용한다.
1
2
3
4
5
6
7
try {
// 실행할 코드
} catch (error) {
// 에러가 발상했을 때 실행할 코드
} finally {
// 항상 실행할 코드
}