1)단락평가
function returnFalse(){
console.log("False함수");
return false;
}
function returnTrue(){
console.log("True 함수");
return true;
}
console.log(returnFalse() && returnTrue());
- returnFalse()가 먼저 호출됨 → "False함수" 출력됨
- returnFalse()의 결과는 false
- false && ... 이므로 뒤의 returnTrue()는 아예 실행되지 않음
2) 객체구조분해할당
let person = {
name: "이정환",
age: 28,
hobby: "테니스"
};
// 3. 객체 구조분해할당을 이용해서 함수의 매개변수를 받는 방법
const func = ({ name, age, hobby, extra }) => {
console.log(name, age, hobby, extra);
};
func(person); // person의 값을 넘김
- func라는 화살표 함수는 매개변수로 객체를 받는데,
- 그 객체 안에 name, age, hobby, extra라는 속성이 있을 거라고 예상하고,
- 그걸 바로 변수로 꺼내서 쓰는 것
왜 extra는 undefined일까?
- person 객체에는 extra라는 속성이 존재하지 않기 때문
- 구조분해할당에서 해당 속성이 없으면, 그 변수는 기본적으로 undefined가 됨
3)spread 연산자
//1.Spread연산자
//객체나 배열에 저장된 여러개의 값을 개별로 흩뿌려주는 역할
let arr1=[1,2,3];
let arr2=[4,...arr1,5,6];
console.log(arr2);
Spread(전개) 연산자는 ... 점 세 개로 표현되며,
배열이나 객체에 담긴 값을 “풀어서 나열”하는 역할을 함
출력결과: [4, 1, 2, 3, 5, 6]
4) 순회와 탐색
let arr1 = [1, 2, 3];
// 모든 요소를 순회하면서 콘솔에 출력
arr1.forEach(function(item, idx, arr) {
console.log(idx, item * 2);
});
//0 2
//1 4
//2 6
// 새로운 배열에 2배 값 추가
let doubledArr = [];
arr1.forEach((item) => {
doubledArr.push(item * 2);
});
console.log(doubledArr); // [2, 4, 6]
- item: 현재 요소의 값
- index: 현재 요소의 인덱스
- array: 원래의 배열
let arr2 = [1, 2, 3];
arr2.includes(3); // 3이 있는지 확인 (리턴값은 true지만, 따로 저장 안 함)
let isIncludes = arr2.includes(3); // 결과를 변수에 저장
console.log(isIncludes); // true
includes 메서드란?
- 형식: 배열.includes(값)
- 배열에 해당 값이 있으면 → true
- 없으면 → false 반환
// indexOf
// 특정 요소의 인덱스(위치)를 찾아서 반환하는 메서드
let arr3 = [1, 2, 3];
let index = arr3.indexOf(2);
console.log(index); // 1
⚠️ objectArr에서 indexOf가 실패하는 이유
let objectArr = [
{ name: "이정환" },
{ name: "홍길동" }
];
console.log(
objectArr.indexOf({ name: "이정환" })
); // -1 (실패)
- indexOf()는 참조값 비교를 함 (객체는 주소값이 다르면 다름)
- {name:"이정환"}는 새로운 객체이기 때문에
기존 배열의 요소들과 주소가 다르다 → -1 반환
---> findIndex를 활용
console.log(
objectArr.findIndex(item => item.name === "이정환")
); // 0 (정확하게 위치 반환)
5)Date 객체와 날짜
Date 객체 생성
let date1 = new Date(); // 현재 날짜와 시간
console.log(date1);
let date2 = new Date("1997-01-07"); // 특정 날짜
console.log(date2);
let ts1 = date1.getTime();
console.log(ts1); // 현재 시간의 밀리초(ms)
let date4 = new Date(ts1); // 다시 날짜로 복원
날짜시간요소 추출
let year = date1.getFullYear();
let month = date1.getMonth() + 1; // 0부터 시작하므로 +1
let date = date1.getDate();
let hour = date1.getHours();
let minute = date1.getMinutes();
let seconds = date1.getSeconds();
날짜수정
date1.setFullYear(2023);
date1.setMonth(2); // 3월 (0부터 시작)
date1.setDate(30);
date1.setMinutes(59);
date1.setSeconds(59);
다양한 출력 포맷
console.log(date1.toDateString()); // 예: "Sat Mar 30 2023"
console.log(date1.toLocaleString()); // 예: "2023. 3. 30. 오후 1:59:59" (한국 기준)
☆발표부분
동기와 비동기?
동기는 여러개의 작업을 순서대로, 하나씩 처리하는 방식이다.

- Task A가 끝날 때까지 Task B, Task C가 기다려야 함
- 즉, 한 줄로 줄 서 있는 것처럼 차례대로 실행
- Task A가 오래 걸리면 전체 흐름이 멈춤

- Task A가 실행되는 동안 쓰레드는 멈추지 않고 계속 진행할 수 있음
- 나중에 Task A의 결과가 필요하면, 그때 콜백, Promise, await 같은 걸로 결과를 가져옴
- 즉, 결과를 기다리지 않고 다음 작업을 할 수 있어서 프로그램이 더 효율적임
console.log(1);
console.log(3);
setTimeout(()=>{
console.log(2);
},3000);//비동기적
console.log(3);
//자바스크립트에는 엔진이 1개밖에없음
setTimeout(...) → 3초 뒤 실행 예약만 해두고, 바로 다음 코드로 넘어감 (비동기)
3초 후 → setTimeout 콜백 실행 → 2 출력
6)비동기 작업 처리하기 -콜백함수
1. orderFood(callback)
function orderFood(callback) {
setTimeout(() => {
const food = "떡볶이";
callback(food);
}, 3000);
}
- orderFood는 3초 후에 "떡볶이"라는 문자열을 콜백 함수에 전달함.
2. cooldownFood(food, callback)
function cooldownFood(food, callback) {
setTimeout(() => {
const cooldownedFood = `식은 ${food}`;
callback(cooldownedFood);
}, 2000);
}
- 전달받은 food를 받아서 식은 떡볶이로 만들어줌 (2초 걸림)
- 식힌 결과를 콜백 함수로 넘김
3. freezeFood(food, callback)
function freezeFood(food, callback) {
setTimeout(() => {
const freezedFood = `냉동된 ${food}`;
callback(freezedFood);
}, 1500);
}
- 식은 떡볶이를 받아서 → 냉동된 식은 떡볶이로 바꿔줌 (1.5초 걸림)
- 결과를 콜백으로 넘김
만약 food를 안넘겨주면?
예를 들어 cooldownFood가 food를 인자로 안 받고 그냥 내부에서 "식은 떡볶이"를 만든다면,
→ freezeFood는 원래 음식이 뭔지 모름
"냉동된 식은"이라는 맥락이 끊김
4. 함수 실행
orderFood((food) => {
console.log(food); // 떡볶이
cooldownFood(food, (cooldownedFood) => {
console.log(cooldownedFood); // 식은 떡볶이
freezeFood(cooldownedFood, (freezedFood) => {
console.log(freezedFood); // 냉동된 식은 떡볶이
});
});
});
- 이 부분은 실제 요리 시작하는 부분
- 순서대로 떡볶이 → 식힘 → 냉동 진행됨
- 비동기라서 각 단계가 끝나야 다음 단계로 넘어감
7)비동기 작업 처리하기- Promise
const promise = new Promise((resolve, reject) => {
// executer 함수: Promise가 실행될 때 바로 호출됨
setTimeout(() => {
console.log("안녕");
reject("왜 실패했는지 이유"); // 실패로 종료
}, 2000);
});
console.log(promise); // 즉시 실행: Promise { <pending> }
setTimeout(() => {
console.log(promise); // 3초 후: Promise { <rejected> '왜 실패했는지 이유' }
}, 3000);
시간 동작
| 0초 | promise 생성됨. 내부 작업(setTimeout)은 2초 대기 |
| 0초 | console.log(promise) 실행 → Promise { <pending> } 출력됨 |
| 2초 | "안녕" 출력됨reject("왜 실패했는지 이유") → 실패 상태로 바뀜 |
| 3초 | console.log(promise) 실행 → Promise { <rejected>: '왜 실패했는지 이유' } 출력됨 |
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const num = 10;
if (typeof num === "number") {
resolve(num + 10); // 성공: 20 반환
} else {
reject("num이 숫자가 아닙니다"); // 실패 메시지
}
}, 2000); // 2초 기다림
});
- 2초 후에 실행되는 코드
- num이 숫자인지 확인해서:
- 맞으면 resolve(20)
- 아니면 reject("num이 숫자가 아닙니다")
promise
.then((value) => {
console.log(value); // 성공 시 실행
})
.catch((error) => {
console.log(error); // 실패 시 실행
});
- .then() → resolve()에서 전달된 값을 받음
- .catch() → reject()에서 전달된 에러 메시지를 받음
시간 설명
| 0초 | new Promise(...) 생성, 내부 setTimeout() 설정됨 |
| 2초 | typeof num === "number" → 참이므로 resolve(20) 실행됨 |
| 즉시 | .then() 안의 코드 실행 → console.log(20) 출력 |
function add10(num) {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (typeof num === "number") {
resolve(num + 10);
} else {
reject("num이 숫자가 아닙니다");
}
}, 2000);
});
return promise;
}
add10(0)
.then((result) => {
console.log(result); // 10
return add10(result); // 10 + 10 = 20
})
.then((result) => {
console.log(result); // 20
return add10(result); // 20 + 10 = 30
})
.then((result) => {
console.log(result); // 30
})
.catch((error) => {
console.log(error); // 에러 발생 시 출력
});
시간 동작 내용
| 0초 | add10(0) 실행 → 2초 대기 시작 |
| 2초 | resolve(10) → 첫 번째 .then() 실행 → console.log(10) 출력 |
| 2초 | add10(10) 실행 → 2초 대기 |
| 4초 | resolve(20) → 두 번째 .then() 실행 → console.log(20) 출력 |
| 4초 | add10(20) 실행 → 2초 대기 |
| 6초 | resolve(30) → 세 번째 .then() 실행 → console.log(30) 출력 |
8)비동기작업 처리하기-async,await
// async : 함수가 자동으로 Promise를 반환하도록 만드는 키워드
async function getData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: "이정환",
id: "winterlood",
});
}, 2000); // 2초 뒤에 resolve 실행
});
}
console.log(getData()); // Promise {<pending>} 출력됨 (2초 대기 중)
// await : async 함수 안에서만 사용 가능
// 비동기 작업이 끝날 때까지 기다림
async function printData() {
const data = await getData(); // getData()의 결과 기다림
console.log(data); // 2초 후 {name:"이정환", id:"winterlood"} 출력
}
printData();
1.async function getData(){...}
- async 키워드가 붙으면 그 함수는 항상 Promise를 반환함.
- 함수 안에서 return한 값은 resolve(값)과 같게 처리됨.
2.new Promise((resolve)=>{...})
- 2초 후 resolve({...}) 호출 → getData()가 반환하는 Promise가 fulfilled 상태로 바뀜.
console.log(getData())
- 지금 즉시 찍으면 Promise { <pending> } (대기 중) 출력됨.
4.async of function printData()
- async 함수 안에서는 await 사용 가능.
- await getData() → getData()가 끝날 때까지 기다린 뒤 결과를 data에 저장.
5.printData()
- 실행 후 2초 뒤 { name:"이정환", id:"winterlood" } 콘솔에 출력됨.