자바 스크립트, 타입 스크립트라는 뜻이다
JS, TS 문법 간략히 정리했다
아예 모르는 것보다는 나을 거 같아서 공부 살짝 했다
TS는 JS에다 몇가지 추가 문법에다가 C처럼 미리 컴파일 하기에 정적이다
둘다 런타임에는 JS다
let x = 1; // 재할당 O (블록 스코프)
const y = 2; // 재할당 X (상수, 객체/배열의 내부 수정은 가능)
var z = 3; // 함수 스코프 + 호이스팅(지양)
typeof 123 // "number" 정수/실수 구분 없음
typeof 10n // "bigint" 아주 큰 정수용 (number와 연산 혼용 불가)
typeof "hi" // "string" 템플릿 리터럴(문자열 안 표현식)도 문자열
typeof true // "boolean" T/F
typeof undefined // "undefined" 미정의 (값이 없음)
typeof null // "object" (역사적 버그) 걍 NULL 말함
typeof {} // "object" 배열도 객체
typeof Symbol() // "symbol" 고유한 식별자 (절대 중복 X)
1 == "1" // true (느슨한 비교, 지양)
1 === "1" // false (엄격 비교, 권장)
타입도 같아야 하냐 안하냐다
if (cond) { ... } else { ... }
for (let i = 0; i < n; i++) { ... } // C와 유사
for (const v of arr) { ... } // 값 순회
for (const k in obj) { ... } // 키 순회(객체용)
switch (x) { case 1: ...; break; default: ... }
function add(a, b = 0) { return a + b } // 기본값
const mul = (a, b) => a * b; // 화살표 함수(간결)
js엔 this라는 함수 호출자가 있는데 (함수 주인이라고 보면된다)
화살표 함수는 this를 만들지 않음
대신 바깥 함수의 this를 물려받아 쓴다
const a = 1, b = 2;
const obj = { a, b, sum() { return this.a + this.b } }; // 키=변수명 단축
const arr = [1, 2, 3];
const {x, y: yy = 10} = { x: 1 }; // x=1, yy=10(기본값)
const [h, ...rest] = [1, 2, 3]; // h=1, rest=[2,3]
const o2 = { ...obj, a: 9 }; // 복사+덮어쓰기
const a2 = [0, ...arr, 4]; // 배열 결합
const name = "Kim";
console.log(`Hello, ${name}!`);
const v = maybeNull ?? 0; // null/undefined면 0
const len = user?.profile?.name?.length; // 안전 접근
class Point {
#x; // private 필드 (#)
constructor(x, y) { this.#x = x; this.y = y; } // x는 private, y는 공개
getX() { return this.#x; }
static origin() { return new Point(0, 0); }
}
class Point3D extends Point { constructor(x, y, z){ super(x,y); this.z=z; } }
// a.js
export const PI = 3.14;
export default function area(r){ return PI * r * r; }
/* --------------------------------- */
// b.js
import area, { PI } from './a.js';
심화하면 좀 어려워서 나중에 따로 다루겠다
const res = await fetch('https://example.com'); // 모듈/최상위 await 가능
// fetch는 promise 반환
const data = await res.json(); // 이것도 promise
try {
const v = await mayFail();
} catch (e) {
console.error(e);
}
Promise는 지금에 결과 없어도 나중에 성공/실패 결과를 준다는 객체다
await은 async 함수 안에서만 사용 가능
await은 Promise 끝날 때까지 기다리고 결과를 값처럼 받음