let x = 10;
x = 20; // 재할당 가능
{
let y = 30;
console.log(y); // 출력: 30
}
console.log(x); // 출력: 20
console.log(y); // 에러: y is not defined
const PI = 3.14;
PI = 3.14159; // 에러: Assignment to constant variable
const person = { name: 'John' };
person.name = 'Jane'; // 가능
person = { name: 'Doe' }; // 에러: Assignment to constant variable
const numbers = [1, 2, 3];
numbers.push(4); // 가능
numbers = [1, 2, 3, 4]; // 에러: Assignment to constant variable
- function 키워드 생략 가능\
// 일반적인 함수 표현식
function add(a, b) {
return a + b;
}
// 화살표 함수
const add = (a, b) => a + b;
배열이나 객체의 요소를 복사하거나 병합할 때 유용하게 활용
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArray = [...arr1, ...arr2];
// combinedArray: [1, 2, 3, 4, 5, 6]
const items = [1, 2, 3]
for (const n of items) {
console.log(n)
}
// 1
// 2
// 3
// 새로운 Map 객체 생성
let myMap = new Map();
// Map에 데이터 추가
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
// 데이터 접근
console.log(myMap.get('key1')); // 출력: value1
// 키 확인
console.log(myMap.has('key1')); // 출력: true
// Map 크기 확인
console.log(myMap.size); // 출력: 2
// Map 반복
for (let [key, value] of myMap) {
console.log(`${key} = ${value}`);
}
// Map 데이터 삭제
myMap.delete('key1');
// Map 데이터 모두 삭제
myMap.clear();
// 새로운 Set 객체 생성
let mySet = new Set();
// Set에 데이터 추가
mySet.add('value1');
mySet.add('value2');
// 값 확인
console.log(mySet.has('value1')); // 출력: true
// Set 크기 확인
console.log(mySet.size); // 출력: 2
// Set 반복
for (let value of mySet) {
console.log(value);
}
// Set 데이터 삭제
mySet.delete('value1');
// Set 데이터 모두 삭제
mySet.clear();
// class 선언
class NewClass {
constructor () { ... } // 생성자
}
// 객체 생성
const c = new NewClass()
// 비동기 함수 정의
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const random = Math.random();
if (random < 0.5) {
resolve(random); // 이행 상태로 처리
} else {
reject(new Error('Operation failed')); // 거부 상태로 처리
}
}, 1000);
});
}
// Promise 사용 예시
asyncOperation()
.then(result => {
console.log('Operation succeeded:', result);
})
.catch(error => {
console.error('Operation failed:', error.message);
});
// Symbol 생성
const symbol1 = Symbol();
const symbol2 = Symbol('description'); // 설명 문자열은 선택적입니다.
console.log(typeof symbol1); // 출력: symbol
console.log(symbol1 === symbol2); // 출력: false
function sum (x, y = 0) {
return x + y
}
sum(10) // 10
function funcName (...args) { }
import name from 'moduleSeoyeong'