변수는 let, const 키워드를 사용하여 선언한다.
let value = 1;
console.log(value); // 1
value = 2;
console.log(value); // 2
const a = 1;
a = 2; // 에러 발생
템플릿 문자열은 문자열 안에 변수와 연산식을 넣을 수 있습니다.
const string1 = '안녕하세요.';
const string2 = '김겨울입니다.';
const greeting = ${string1} + ' ' + ${string2};
// 병합 연산자를 사용한 문자열 연결
const cat = {
kind: '러시안블루',
age: '1살',
};
const catInfo = `저는 ${cat.kind}이고, ${cat.age}입니다.`;
// 백틱(`)을 사용한 문자열 표현을 리터럴 문자열이라고 합니다.
const multiLine = '문자열을 \n여러 줄에 걸쳐 작성하면 \n줄바꿈이 됩니다.';
// 줄바꿈을 할 때는 이스케이프 시퀀스(\n)를 사용합니다.
const number1 = 1;
const number2 = 2;
const result = `${number1} * ${number2} = ${number1 * number2}`;
const boolean = true;
const booleanResult = '블리언 값은' + (boolean ? '참' : '거짓') + '입니다.';
제 이름은 [odada]이고 나이는 [100]살입니다.
전화번호는 [010-1234-5678]이고 주소는 [서울시]입니다.
조건 ? 참 : 거짓
console.log(true ? 1 : 2); // 1
console.log(false ? 1 : 2); // 2
const p = 1;
if (p < 3) {
console.log('참!!'); // 참!!
} else {
console.log('거짓'); // 거짓
}
console.log(p < 3 ? '참!!' : '거짓') // 참!!
function isAnimal(text) {
return text === '고양이' ? '고양이' : '고양이 아님';
}
console.log(isAnimal('고양이')); // 고양이
console.log(isAnimal('개')); // 고양이 아님
...a, ...b
const q = [1, 2, 3];
const r = [4, 5, 6];
const s = q.concat(r); // concat 메서드 사용
console.log(s); // [ 1, 2, 3, 4, 5, 6 ]
const t = [...q, ...r]; // 전개 연산자
console.log(t); // [ 1, 2, 3, 4, 5, 6 ]
const dog = {
name: '멍멍이',
};
const dogInfo = {
...dog,
age: 2,
};
console.log(dogInfo); // { name: '멍멍이', age: 2 }
function sum(a, b, c) {
console.log(a + b + c);
}
sum(1, 2, 3); // 6
// 배열 데이터를 인자로 전달하려면?
const num = [1, 2, 3];
sum(num[0], num[1], num[2]); // 6 (기존 방식)
// 전개 연산자를 사용하면?
sum(...num); // 6
비구조화 할당은 객체와 배열로부터 속성이나 요소를 쉽게 꺼낼 수 있습니다.
const object = { a: 1, b: 2 };
const { a, b } = object;
console.log(a); // 1
console.log(b); // 2
// 비구조화 할당을 하는 과정에서 이름을 바꿀 수도 있습니다.
const object = { a: 1, b: 2 };
const { a: c, b: d } = object; // a -> c, b -> d
console.log(c); // 1
console.log(d); // 2
// 비구조화 할당을 하는 과정에서 기본값을 설정할 수도 있습니다.
const object = { a: 1 };
const { a, b = 2 } = object;
console.log(a); // 1
console.log(b); // 2
// 비구조화 할당을 하는 과정에서 함수의 인수에서도 사용할 수 있습니다.
const object = { a: 1 };
function print({ a, b = 2 }) {
console.log(a);
console.log(b);
}
print(object); // 1, 2
const array = [1, 2];
const [one, two] = array;
console.log(one); // 1
console.log(two); // 2
// 비구조화 할당을 하는 과정에서 기본값을 설정할 수도 있습니다.
const array = [1];
const [one, two = 2] = array;
console.log(one); // 1
// 비구조화 할당을 하는 과정에서 함수의 인수에서도 사용할 수 있습니다.
const array = [1, 2];
function print([one, two]) {
console.log(one);
console.log(two);
}
print(array); // 1, 2
함수의 인수에서도 비구조화 할당을 사용할 수 있습니다.
function add({ a, b }) {
// 비구조화 할당
return a + b;
}
const result = add({ a: 1, b: 2 }); // 인수에 객체를 넣어서 호출
console.log(result); // 3
클래스는 ES6에서 새롭게 도입된 문법입니다. 기존에 존재하던 프로토타입을 베이스로 하고 있습니다.
// 클래스를 선언할 때는 class 키워드를 사용하고 클래스 이름은 파스칼 케이스로 작성합니다.
class Animal {
// constructor 메서드를 작성하여 생성자를 설정합니다.
constructor(type) {
this.type = type; // 클래스의 초기 상태를 설정합니다.
}
// 클래스 내부에서 함수를 선언할 때는 function 키워드를 생략한 메서드를 작성합니다.
type() {
console.log(this.type); // 클래스 내부에서 멤버 변수를 선언할 때는 const, let, var 키워드를 사용하지 않습니다.
}
}
const dog = new Animal('개');
const cat = new Animal('고양이');
dog.type(); // 개
cat.type(); // 고양이
class Animal {
constructor(type) {
this.type = type;
}
type() {
console.log(this.type);
}
}
class Cat extends Animal {
constructor(type, name, sound) {
super(type); // super 키워드를 사용하여 부모 클래스의 constructor 메서드를 호출합니다.
this.name = name;
this.sound = sound;
}
sound() {
console.log(this.sound);
}
}
const cat = new Cat('고양이', '나비', '야옹');
cat.type(); // 고양이
cat.sound(); // 야옹
cat.name(); // cat.name은 메소드가 아니라서 실행이 안됨
화살표 함수는 function 키워드 대신 => 를 사용하여 좀 더 간략한 방법으로 함수를 선언할 수 있습니다.
function add1(x, y) {
return x + y;
}
const add2 = (x, y) => {
return x + y;
};
const add3 = (x, y) => x + y;
const add4 = (x, y) => ({ x: x, y: y });
function not1(x) {
return !x;
}
const not2 = (x) => !x;
const cat = {
name: '나비',
sound: '야옹',
say: function () {
console.log(this.sound); // 야옹
},
};
cat.say();
const dog = {
name: '멍멍이',
sound: '멍멍',
};
dog.say = cat.say;
dog.say(); // 멍멍
const dog = {
name: '멍멍이',
sound: '멍멍',
};
dog.say = cat.say.bind(dog);
dog.say(); // 멍멍
const cat = {
name: '나비',
sound: '야옹',
say: function () {
console.log(this.sound); // 야옹
},
};
cat.say();
const dog = {
name: '멍멍이',
sound: '멍멍',
};
dog.say = cat.say.bind(dog);
dog.say(); // 멍멍
const catSay = cat.say;
catSay(); // 야옹
const catSay2 = cat.say.bind(cat);
catSay2(); // 야옹
const catSay3 = cat.say.bind(dog);
catSay3(); // 멍멍
객체 리터럴은 중괄호({})를 사용하여 객체를 선언하는 것을 의미합니다.
const dog = {
name: '멍멍이',
age: 2,
sound: '멍멍',
say() {
// say: function() {}의 축약형
console.log(this.sound);
},
};
dog.say(); // 멍멍
const name = '멍멍이';
const age = 2;
const sound = '멍멍';
const dog = {
name: name,
age: age,
sound: sound,
say() {
console.log(this.sound);
},
};
dog.say(); // 멍멍
const name = '멍멍이';
const age = 2;
const sound = '멍멍';
const dog = {
name,
age,
sound,
say() {
console.log(this.sound);
},
};
dog.say(); // 멍멍
배열 내장 함수는 배열을 다룰 때 유용한 함수입니다.
const array = [1, 2, 3, 4];
array.forEach((num) => {
console.log(num);
});
// 1
// 2
// 3
// 4
const array = [1, 2, 3, 4];
const squared = array.map((n) => n * n);
console.log(squared); // [ 1, 4, 9, 16 ]
// 1 * 1 = 1
// 2 * 2 = 4
// 3 * 3 = 9
// 4 * 4 = 16
const array = ['사과', '바나나', '포도', '사과'];
console.log(array.indexOf('사과')); // 0
console.log(array.indexOf('바나나')); // 1
console.log(array.indexOf('포도')); // 2
console.log(array.indexOf('수박')); // -1
const array = ['사과', '바나나', '포도', '사과'];
console.log(array.findIndex((fruit) => fruit === '사과')); // 0
console.log(array.findIndex((fruit) => fruit === '바나나')); // 1
console.log(array.findIndex((fruit) => fruit === '포도')); // 2
console.log(array.findIndex((fruit) => fruit === '수박')); // -1
const array = ['사과', '바나나', '포도', '사과'];
console.log(array.find((fruit) => fruit === '사과')); // 사과
console.log(array.find((fruit) => fruit === '바나나')); // 바나나
console.log(array.find((fruit) => fruit === '포도')); // 포도
console.log(array.find((fruit) => fruit === '수박')); // undefined
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const even = array.filter((n) => n % 2 === 0); // 짝수만 추출
console.log(even); // [ 2, 4, 6, 8 ]
const array = [1, 2, 3, 4, 5];
const index = array.indexOf(2); // 2의 인덱스를 찾아서
array.splice(index, 1); // 2의 인덱스부터 1개를 지웁니다.
console.log(array); // [ 1, 3, 4, 5 ]
const array = [1, 2, 3, 4, 5];
const sliced = array.slice(0, 2); // 인덱스 0부터 2까지 잘라낸다.
console.log(sliced); // [ 1, 2 ]
console.log(array); // [ 1, 2, 3, 4, 5 ]
const array = [1, 2, 3, 4, 5];
const shifted = array.shift(); // 첫 번째 원소를 추출합니다.
console.log(shifted); // 1
console.log(array); // [ 2, 3, 4, 5 ]
const array = [1, 2, 3, 4, 5];
const popped = array.pop(); // 마지막 원소를 추출합니다.
console.log(popped); // 5
console.log(array); // [ 1, 2, 3, 4 ]
const array = [1, 2, 3, 4, 5];
array.push(6); // 마지막에 6을 추가합니다.
console.log(array); // [ 1, 2, 3, 4, 5, 6 ]
const array = [1, 2, 3, 4, 5];
array.unshift(0); // 첫 번째에 0을 추가합니다.
console.log(array); // [ 0, 1, 2, 3, 4, 5 ]
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const concated = array1.concat(array2);
console.log(concated); // [ 1, 2, 3, 4, 5, 6 ]
const array = [1, 2, 3, 4, 5];
console.log(array.join()); // 1,2,3,4,5
console.log(array.join(' ')); // 1 2 3 4 5
console.log(array.join(', ')); // 1, 2, 3, 4, 5
const array = [1, 2, 3, 4, 5];
const result = array.reduce((accumulator, current) => {
// accumulator는 누적값, current는 현재값
console.log({ accumulator, current }); // 누적값과 현재값을 출력
return accumulator + current; // 누적값 + 현재값
}, 0); // 초기값 0
console.log(result);
비동기 처리는 특정 코드의 연산이 끝날 때까지 코드의 실행을 멈추지 않고 다음 코드를 먼저 실행하는 자바스크립트의 특성을 의미합니다.
function work() {
setTimeout(() => {
const start = Date.now(); // 현재 시각을 저장하고
for (let i = 0; i < 1000000000; i++) {} // 0 ~ 999999999까지 반복문을 실행한 후
const end = Date.now(); // 현재 시각을 저장합니다.
console.log(end - start + 'ms'); // 걸린 시간을 밀리초로 출력합니다.
}, 0); // 0ms 이후에 콜백 함수를 실행합니다.
}
console.log('작업 시작!'); // 작업 시작!이 먼저 출력됩니다.
work(); // work 함수를 호출합니다.
console.log('다음 작업'); // 다음 작업이 먼저 출력됩니다.
// '작업 시작'과 '다음 작업'이 먼저 출력되고
// 위에 for문을 1000000000번 반복하는 반복문을 실행하는 동안에는 다른 작업을 할 수 없기 때문에 브라우저가 멈춰있는 것처럼 보입니다.
// 1000000000번 반복하는 반복문이 실행되고 걸린 시간을 출력합니다.
// 이것이 비동기 처리로 작업이 끝날 때까지 기다리지 않고 다음 작업을 수행하는 것을 의미합니다.
function work(callback) {
setTimeout(() => {
const start = Date.now();
for (let i = 0; i < 1000000000; i++) {}
const end = Date.now();
console.log(end - start + 'ms');
callback(end - start);
}, 0);
}
console.log('작업 시작!');
work((ms) => {
// 콜백 함수를 전달합니다.
console.log('작업이 끝났어요!');
console.log(ms + 'ms 걸렸다고 해요.');
});
console.log('다음 작업');
// n은 숫자, callback은 함수
function increaseAndPrint(n, callback) {
// 1초 후에 실행
setTimeout(() => {
const increased = n + 1; // n을 1씩 더하기
console.log(increased); // 출력하기
// callback이 있으면
if (callback) {
callback(increased); // callback 함수 호출하기
}
}, 1000);
}
increaseAndPrint(
0, // n은 0
(n) => {
// callback 함수
increaseAndPrint(
n, // n은 1
(n) => {
// callback 함수
increaseAndPrint(
n, // n은 2
(n) => {
// callback 함수
increaseAndPrint(
n, // n은 3
(n) => {
// callback 함수
increaseAndPrint(
n, // n은 4
(n) => {
// callback 함수
console.log('작업 끝!'); // 출력
}
);
}
);
}
);
}
);
}
);
const myPromise = new Promise((resolve, reject) => {
// 새 Promise 객체를 만들 때는 new Promise를 사용합니다.
// 새 Promise 객체를 만들 때는 함수를 선언합니다.
// 이 함수는 resolve와 reject를 인자로 가집니다.
// resolve와 reject는 함수입니다.
// resolve는 성공했을 때 호출하고, reject는 실패했을 때 호출합니다.
// 이 함수 내부에 비동기 작업을 넣습니다.
// 작업이 끝나면 resolve 혹은 reject를 호출합니다.
// resolve와 reject는 값을 인자로 가집니다.
// reject의 인자를 통해 에러 객체를 넣을 수 있습니다.
// 보통 작업이 성공하면 resolve, 실패하면 reject를 사용합니다.
setTimeout(() => {
resolve('result'); // 1초 뒤에 result라는 값을 넣습니다.
}, 1000);
});
// myPromise가 끝나면
myPromise.then((result) => {
console.log(result); // result 값을 출력합니다.
});
function increaseAndPrint(n) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const value = n + 1;
if (value === 5) {
const error = new Error();
error.name = 'ValueIsFiveError';
reject(error);
return;
}
console.log(value);
resolve(value);
}, 1000);
});
}
increaseAndPrint(0)
.then((n) => {
return increaseAndPrint(n);
})
.then((n) => {
return increaseAndPrint(n);
})
.then((n) => {
return increaseAndPrint(n);
})
.then((n) => {
return increaseAndPrint(n);
})
.then((n) => {
return increaseAndPrint(n);
})
.catch((e) => {
console.error(e);
});
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function process() {
console.log('안녕하세요!');
await sleep(1000); // 1초쉬고
console.log('반갑습니다!');
}
process();
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function makeError() {
await sleep(1000);
const error = new Error();
throw error;
}
async function process() {
try {
await makeError();
} catch (e) {
console.error(e);
}
}
process();