let a = 5;, b = 10;
[a, b] = [b, a];
console.log(a, b) // 10, 5
// 루프를 사용한 예시 코드
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = [];
for (let i = 0; i < numbers.length; i++) {
doubledNumbers.push(numbers[i] * 2);
}
console.log(doubledNumbers); // 출력: [2, 4, 6, 8, 10]
// 함수형 프로그래밍 방식으로 루프를 제거한 예시 코드
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((num) => num * 2);
console.log(doubledNumbers); // 출력: [2, 4, 6, 8, 10]
const numbers = [1, 2, 3, 4, 4, 5, 5, 6];
// Set을 사용하여 중복 제거
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // 출력: [1, 2, 3, 4, 5, 6]
const person = {
name: 'Lee Sun-Hyoup',
familyName: 'Lee',
givenName: 'Sun-Hyoup'
};
const company = {
name: 'Cobalt. Inc.',
address: 'Seoul'
};
const leeSunHyoup = { ...person, ...company };
console.log(leeSunHyoup);
// {
// name: 'Cobalt. Inc.', 같은 키는 마지막에 대입된 값으로 정해진다.
// familyName: 'Lee',
// givenName: 'Sun-Hyoup',
// address: 'Seoul'
// }
// ||를 활용한 기본값 설정
function greet(name) {
name = name || "Guest";
console.log(`Welcome, ${name}!`);
}
greet("Alice"); // 출력: Welcome, Alice!
greet(); // 출력: Welcome, Guest!
/// &&을 활용한 조건부 실행
const user = {
name: "Hyojin",
isAdmin: true,
hasPermission: true,
};
// isAdmin이 true이고 hasPermission이 true일 때만 실행
user.isAdmin && user.hasPermission && console.log("관리자 권한 확인됨");
const user = {
name: "Alice",
age: 25, city:
"New York"
};
const { name, age, city } = user;
console.log(name); // 출력: Alice
console.log(age); // 출력: 25
console.log(city); // 출력: New York
const name = "Alice";
const age = 25;
const user = { name, age };
console.log(user); // 출력: { name: "Alice", age: 25 }
배열이나 객체에서 원하는 요소를 추출하여 개별 변수로 할당하는 기능이다.
코드를 간결하게 작성하고 필요한 데이터에 쉽게 접근할 수 있다.
함수에 객체를 넘길 경우 필요한 것만 꺼내 쓸 수 있다.
배열 비구조화 할당
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
이 코드에서 [first, second, ...rest]는 배열 numbers의 첫 번째 요소를 first 변수에, 두 번째 요소를 second 변수에 할당하고, 나머지 요소들을 rest 배열에 할당한다. 이를 통해 배열의 각 요소에 간편하게 접근할 수 있다.
함수에 객체를 전달하는 경우,
함수의 매개변수를 비구조화하여 원하는 객체의 프로퍼티에 접근할 수 있다.
function printUser({ name, age, city }) {
return name, age, city
}
const user = { name: "Alice", age: 25, city: "New York" };
console.log(user);
const nameKey = 'name';
const emailKey = 'email';
const person = {
[nameKey]: 'Lee Sun-Hyoup',
[emailKey]: 'kciter@naver.com'
};
console.log(person);
// {
// name: 'Lee Sun-Hyoup',
// email: 'kciter@naver.com'
// }
const values = [0, null, "", undefined, NaN, 123, "Hello"];
const converted = values.map(value => !!value);
console.log(converted);
// [false, false, false, false, false, true, true]