JavaScript
웹 브라우저 + Node.js에서 동작하는 동적 타입 언어. 현재는 TypeScript와 함께 사용하는 것이 표준.
변수
const name = "김탄" // 불변 (권장)
let count = 0 // 가변
// var 사용 지양 — 함수 스코프, 호이스팅 문제자료형
// Primitive
typeof "str" // string
typeof 42 // number
typeof true // boolean
typeof undefined // undefined
typeof null // object (역사적 버그)
typeof Symbol() // symbol
typeof 9007n // bigint
// Reference
typeof {} // object
typeof [] // object
typeof function(){} // function함수
// 함수 선언식 (호이스팅 O)
function add(a, b) { return a + b }
// 화살표 함수 (this 바인딩 없음)
const add = (a, b) => a + b
const greet = name => `안녕, ${name}`
// 기본값 / 나머지 매개변수
function fn(a, b = 0, ...rest) {}
// 구조분해
function fn({ name, age = 0 }) {}배열 메서드
const nums = [1, 2, 3, 4, 5]
nums.map(x => x * 2) // [2,4,6,8,10]
nums.filter(x => x > 2) // [3,4,5]
nums.reduce((acc, x) => acc + x, 0) // 15
nums.find(x => x > 3) // 4
nums.findIndex(x => x > 3) // 3
nums.some(x => x > 4) // true
nums.every(x => x > 0) // true
nums.includes(3) // true
nums.flat() // 중첩 배열 펼치기
nums.flatMap(x => [x, x*2]) // map 후 flat객체
const user = { name: "김탄", age: 30 }
// 구조분해
const { name, age } = user
const { name: userName } = user // 별칭
// 스프레드
const updated = { ...user, age: 31 }
// 옵셔널 체이닝
user?.address?.city // undefined (에러 없음)
// Nullish 병합
user.email ?? "기본값" // null/undefined일 때만 기본값비동기
// Promise
fetch('/api/users')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err))
// async/await (권장)
async function getUsers() {
try {
const res = await fetch('/api/users')
const data = await res.json()
return data
} catch (err) {
console.error(err)
}
}
// 병렬 실행
const [users, posts] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
])
// 에러 무시하고 결과만
const results = await Promise.allSettled([p1, p2])클래스
class Animal {
#name // private 필드
constructor(name) {
this.#name = name
}
get name() { return this.#name }
speak() { return "" }
}
class Dog extends Animal {
speak() { return `${this.name}: 왈왈` }
}모듈 (ESM)
// 내보내기
export const PI = 3.14
export function add(a, b) { return a + b }
export default class MyClass {}
// 가져오기
import MyClass, { PI, add } from './math.js'
import * as math from './math.js'
// 동적 import
const module = await import('./heavy.js')유용한 패턴
// 단락 평가
const name = user && user.name
// 배열 고유값
const unique = [...new Set(arr)]
// 객체 깊은 복사 (단순한 경우)
const copy = JSON.parse(JSON.stringify(obj))
// 딜레이
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
await sleep(1000)
// 이벤트 한 번만
element.addEventListener('click', handler, { once: true })