if(123) ---- Truthy
if(undefined) ---- Falsy
let f1 = undefined;
let f2 = null;
let f3 = 0;
let f4 = -0;
let f5 = NaN;
Slet f6 = "";
let f7 = 0n; // Big Integer라는 특수한 자료형. 잘 사용되지 않는다.
// -> 7가지 Falsy 한 값들 제외한 나머지 모든 값
let t1 = "hello";
let t2 = 123;
let t3 = [];
let t4 = {};
let t5 = () => {};
// 객체를 받을 것이라고 생각했는데 undefined인 값이 넘어오는 경우가 정말 많음
function printName(person) {
if (!person) {
console.log("person의 값이 없음");
return;
}
console.log(person.name);
}
let person = { name: "이정환" };
printName(person);
// 기존 코드
function printNameOld(person) {
if(!person) {
console.log("person의 값이 없음");
return;
}
console.log(person.name);
}
// 단락 평가 활용 사례
// && = And = 하나라도 false이면 false
function printName(person) {
const name = person && person.name;
console.log(name || "person의 값이 없음");
}
printName();
printName({ name: "이정환" });
let arr = [1, 2, 3];
let [one, two, three, four = 4] = arr;
let person = {
name: "이정환",
age: 27,
hobby: "테니스",
};
let {
age: myAge,
hobby,
name,
extra = "hello",
} = person;
const func = ({ name, age, hobby, extra }) => {
console.log(name, age, hobby, extra);
};
func(person);
...let arr1 = [1, 2, 3];
let arr2 = [4, ...arr1, 5, 6];
let obj1 = {
a: 1,
b: 2,
};
let obj2 = {
...obj1,
c: 3,
d: 4,
};
function funcA(p1, p2, p3) {
// console.log(p1, p2, p3);
}
funcA(...arr1);
function funcB(one, two, ...ds) {
console.log(ds); // 3
}
funcB(...arr1);
// 얕은 복사 - 참조값 복사 => 원본 객체가 수정될 수 있음
let o1 = {name : "이정환"};
let o2 = o1;
// 깊은 복사 - 새로운 객체 생성, 프로퍼티만 따로 복사
let o3 = { ...o1 };
// 얕은 비교
console.log(o1 == o2); // true
console.log(o1 == o3); // false
// 깊은 비교 - 프로퍼티의 값을 비교
// JSON.stringify : 객체를 문자열로 변환하는 기능
console.log(
JSON.stringify(o1) == JSON.stringify(o3) // true
);
for of는 Array에만 사용할 수 있음. for in은 객체에만 사용할 수 있음let arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
for (let item of arr) {
console.log(item);
}
let person = {
name: "이정환",
age: 27,
hobby: "테니스",
};
let keys = Object.keys(person); // ['name', 'age', 'hobby']
for (let key of keys) {
const value = person[key];
console.log(key, value);
}
let values = Object.values(person); // ['이정환', 27, '테니스']
for (let value of values) {
console.log(value);
}
for (let key in person) {
const value = person[key];
console.log(key, value);
}
![]() | ![]() |
|---|
slice(startIndex, endIndex) : startIndex ~ endIndex-1에 해당하는 배열 반환let arr1 = [1, 2, 3];
arr1.forEach(function (item, idx, arr) {
console.log(idx, item*2);
});
-1을 반환-1을 반환let objectArr = [
{ name: "이정환" },
{ name: "홍길동" },
];
console.log(
objectArr.indexOf({ name: "이정환" }) // -1
);
console.log(
objectArr.findIndex(
(item) => item.name === "이정환"
)
); // 0
let arr1 = [
{ name: "이정환", hobby: "테니스" },
{ name: "김효빈", hobby: "테니스" },
{ name: "홍길동", hobby: "독서" },
];
const tennisPeople = arr1.filter(
(item) => item.hobby === "테니스"
); // [{...}, {...}]
let arr2 = [1, 2, 3];
const mapResult1 = arr2.map((item, idx, arr) => {
return item * 2;
});
let names = arr1.map((item) => item.name);
let arr3 = [10, 3, 5];
// 내림차순 정렬
arr3.sort((a, b) => {
if (a > b) {
// a가 b 앞에 와라
return -1;
} else if (a < b) {
// b가 a 앞에 와라
return 1;
} else {
// 두 값의 자리를 바꾸지 마라
return 0;
}
});
let arr5 = ["c", "a", "b"];
const sorted = arr5.toSorted();
console.log(arr5);
console.log(sorted);
let arr6 = ["hi", "im", "winterlood"];
const joined = arr6.join(" ");
console.log(joined); // hi im winterlood
let date1 = new Date(); // 생성자. 현재시간.
let date2 = new Date(1997, 1, 7, 23, 59, 59);
let ts1 = date1.getTime();
let date4 = new Date(ts1);
let year = date1.getFullYear();
let month = date1.getMonth() + 1;
let date = date1.getDate();
let hour = date1.getHours();
let minute = date1.getMinutes();
let seconds = date1.getSeconds();
date1.setFullYear(2023);
date1.setMonth(2);
date1.setDate(30);
date1.setHours(23);
date1.setMinutes(59);
date1.setSeconds(59);
console.log(date1.toDateString()); // Thu Mar 30 2023
console.log(date1.toLocaleString()); // 2023. 3. 30. 오후 11:59:59
여러 개의 작업(쓰레드)을 하나씩 처리하는 흐름
Javascript는 기본적으로 동기적으로 실행된다.
다른 언어는 멀티스레드 방식을 지원하나, Javascript 엔진에는 스레드가 하나
비동기로 구성하되, 결과값을 이용하고 싶다면 callback함수를 호출하는 방식으로 구성할 수 있다.
비동기 작업들은 자바스크립트 엔진이 아닌 Web APIs에서 실행됨

Web APIs는 웹 브라우저가 직접 관리하는 별도의 영역

function add(a, b, callback) {
setTimeout(() => {
const sum = a + b;
callback(sum);
}, 3000);
}
add(1, 2, (value) => {
console.log(value);
});
// 음식을 주문하는 상황
function orderFood(callback) {
setTimeout(() => {
const food = "떡볶이";
callback(food);
}, 3000);
}
function cooldownFood(food, callback) {
setTimeout(() => {
const cooldownedFood = `식은 ${food}`;
callback(cooldownedFood);
}, 2000);
}
function freezeFood(food, callback) {
setTimeout(() => {
const freezedFood = `냉동된 ${food}`;
callback(freezedFood);
}, 1500);
}
// indent가 깊어진 상황
orderFood((food) => {
console.log(food);
cooldownFood(food, (cooldownedFood) => {
console.log(cooldownedFood);
freezeFood(cooldownedFood, (freezedFood) => {
console.log(freezedFood);
});
});
});


executor 함수 : 프로미스 객체를 생성하면서 인수로 전달되는 콜백 함수PromiseState를 fulfilled 혹은 rejected로 바꾸며, 함수의 인수로 결과값을 전달해줘야 Promise객체의 PromiseResult의 값이 바뀐다.resolve : 프로미스 작업(비동기 작업)을 성공 상태로 바꾸는 함수reject : 프로미스가 관리하는 비동기 작업을 실패 상태로 바꾸는 함수Promise.then() : fulfilled 상태일때 실행Promise.catch() : reject 상태일때 실행then()과 catch()는 별도의 return문이 없으면 원본 Promise객체를 반환함. 또한 필요에 따라 새로운 Promise 객체를 반환하도록 구성할 수 있음. 따라서 Promise.then().catch() 와 같은 식으로 연결하여 표현이 가능함.function add10(num) {
const promise = new Promise((resolve, reject) => {
// 비동기 작업 실행하는 함수
// executor
setTimeout(() => {
if (typeof num === "number") {
resolve(num + 10);
} else {
reject("num이 숫자가 아닙니다");
}
}, 2000);
});
return promise;
}
add10(0)
.then((result) => { // then : fulfilled 상태일때 실행
console.log(result);
return add10(result);
})
.then((result) => {
console.log(result);
return add10(undefined);
})
.then((result) => {
console.log(result);
})
.catch((error) => { // catch : rejected 상태일 때 실행
console.log(error);
});
async function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
name: "이정환",
id: "winterlood",
});
}, 1500);
});
}

// await를 안쓸경우
async function pringData() {
getData().then((result) => {
console.log(result);
});
}
// await를 쓸 경우
async function printData() {
const data = await getData();
console.log(data);
}
printData();