+ : 더하기 연산자- : 빼기 연산자* : 곱하기 연산자/ : 나누기 연산자% : 나머지 연산자let x = 2;
const y = 3; // 재할당이 불가능한 변수 선언 방식
console.log((x = x * y)); // 4 * 3
// Expected output: 12
+, -, *, /, % 뒤에 = 을 붙여 값을 재할당할 수도 있다.let x = 3;
const y = 4;
x *= y; // 4 * 3
console.log(x) // Expected output: 12
++--let a = 3;
console.log(a++); // 3
console.log(a); // 4
console.log(--a); // 3
boolean 데이터로 출력이 된다.! 하나 당 부정을 뜻하고, 중복해서 사용이 가능하다.console.log(![]) // false
console.log(!{}) // false
console.log(!!null) // true
a == b : 값이 같은지 비교 (형 변환이 자동으로 발생한다.) a === b : 데이터가 같은지 비교a !== b : 두 값이 불일치하는지 비교하는 연산자>, <, >=, <= : 값의 크기를 비교하는 연산자 🐣 AND 연산자 : a && b
🐣🐣 데이터가 모두 참일 경우에만 true값이 반환되고, 하나라도 거짓인 경우 false값이 반환된다.
console.log(true && false) // false
🐣🐣모든 데이터가 true일 경우 가장 마지막에 있는 데이터가 출력된다.
console.log('A' && 'B' && 'C') // C
🐣🐣데이터들 중에 false 데이터가 있을 경우, 가장 왼쪽에서부터 만나는 false 데이터의 값을 반환한다.
console.log(1 && 0) // 0
console.log(1 && 2 && 0) // 0
console.log(1 && 0 && 2) // 0
console.log(0 && 1) // 0
console.log('A' && 'B' && '') // ''
🐣OR 연산자 : a || b
🐣🐣 하나라도 true인 데이터가 있는 경우 true값이 반환되고, 데이터가 모두 거짓일 때만 false값이 반환된다.
let a = ture;
let b = false;
if (a || b) {
console.log('Apple')
} // Apple
🐣🐣 값이 ture인 데이터를 출력한다. (true 데이터가 여러개일 경우엔 가장 왼쪽에서부터 첫번째로 만나는 true 데이터가 반환된다.)
console.log( 1 || 0 ) // 1
console.log('null' || '1') // 1
console.log(flase || 0 || {}) // {}
console.log(function () {} || 1 || 0) // function () {}
🐣🐣모든 데이터가 거짓인 경우엔 가장 마지막에 있는 false 데이터가 반환된다.
console.log(false || 0 || NaN) // NaN
null, undefined 값만 건너뛴다. 즉, null, undefined가 아닌 값을 가진 데이터는 모두 반환된다.null 또는 undefined 데이터가 아닌 데이터를 반환한다.a ?? bnull 또는 undefined일 경우엔 가장 마지막 데이터가 반환된다. const n = 0
const num = n ?? 7
console.log(num) // 0
// OR 연산자를 사용하면 반환되는 값은 7이 된다.
let a = false
console.log (a ?? 1 ?? 2) // false
조건 ? '첫 번째 값' : '두 번째 값'const a = 1
if (a < 2) {
console.log('Apple')
} else {
console.log('Banana')
} // Apple
console.log (a < 2? 'Apple' : 'Banana') // Apple
🐣응용 ver.
// 삼항 연산자로 함수 정의하기
function favoriteFruits(fruitName) {
return fruitName // return은 함수 내부의 값을 외부로 보내준다.
? fruitName
: 'none'
}
console.log(favoriteFruits('Apple')) // Apple
console.log(favoritefruits('')) // none
...은 하나로 뭉쳐 있는 여러 값들의 집합을 펼쳐서 개별적인 값들의 목록으로 만든다.let arr = [1, 2, 3];
console.log(...arr); // 1, 2, 3
스프레드 문법 적용 대상은 Array, String, Map, Set, DoM 컬렉션, arguments과 같이 for...of 문으로 순회할 수 있는 이터러블에 한정된다.
전개 연산자의 결과는 값이 아닌, 개별적인 값들의 목록이다. 피연산자를 연산해 값을 생성하는 연산자가 아니기 때문이며, 값이 아니기에 변수에 할당할 수 없다.
스프레드 문법의 결과물은 '쉼표로 구분한 값의 목록을 사용하는 문맥'에서만 사용 가능하다.
🐣쉼표로 구분한 값의 목록을 사용하는 문맥 :
🐣🐣1. 함수 호출문의 인수 목록
요소들이 집한인 배열을 펼쳐서 개별적인 값들의 목록으로 만든 후,
이를 함수의 인수 목록으로 전달해야 하는 경우 사용한다.
예제1
let arr = [1, 2, 3];
const max = Math.max(arr); // NaN
Math.max 메서드는 개수가 정해져 있지 않은 여러 개의 숫자를 인수로 전달받아 인수 중에서 최댓값을 반환한다. 따라서 NaN이 출력된다.예제2
let arr = [1, 2, 3];
const max = Math.max(...arr); // 3
🐣🐣2. 배열 리터럴의 요소 목록
concat() 메소드 보다 더 간단하게 할 수 있다. (객체 데이터 또한 같은 방식으로 합칠 수 있다. 자세한 건 배열 리터럴 다음에 살펴보도록 한다.)예제
const a = [1, 2, 3]
const b = [4, 5, 6]
const c = a.concat(b) // ES5에서 사용하던 방식
console.log(c) // 1, 2, 3, 4, 5, 6
const d = [...a, ...b] // 스프레드 연산자로 병합
console.log(d) // 1, 2, 3, 4, 5, 6
🐣🐣3. 객체 리터럴의 프로퍼미 목록
Object.assign() 메소드를 이용하는 것이었다. 더욱 간소화된 지금은 어떻게 변했는지 예제를 보도록 한다. 예제
const a = { x: 1, y: 2 };
const b = { y: 3, z: 4 };
const c = Object.assign({}, a, b); // 기존 ES5 방식
console.log(c); // x: 1, y: 3, z: 4
// 객체 데이터 각각의 속성은 고유하다는 특징으로 인해 기존 변수 y는 다음으로 나오는 y로 덮어쓰워진다.
const d = {...a, ...b};
console.log(d); // x: 1, y: 3, z: 4
//방법1 - Array
let arr1 = [1, 2, 3];
const [a, b, c,] = arr1;
console.log (a, b, c); // 1, 2, 3
//방법2
let a = 1;
let b = 2;
let c = 3;
let arr2 = [5, 6, 7];
[a, b, c] = arr2;
console.log(a, b, c) // 5, 6, 7
//방법3
const arr3 = ['Apple', 'Melon', 'Red', 'Green'];
const [f1, f2, ...colors] = arr3
console.log(f1, f2, ...colors); // Apple, Melon, Red, Green
//방법4 - Object
const obj = {
a: 'I',
b: 'love',
c: 'myself.'
}
const {a, b, c} = obj; // const a = obj.a
// const b = obj.b
// const c = obj.c
// 와 같은 로직
console.log(a, b, c); // I love myself.
예제
// 배열 데이터
arr = [1, 2, 3, 4];
const [a, ...rest] = arr
console log(a, rest); // 1, 2, 3, 4
// 객체 데이터
obj = {
b: 1,
c: 2,
d: 3,
}
const {c, ...rest} = obj;
console.log(c, rest); // 2
// (b: 1, d: 3)
const {f, g, h} = obj;
console.log(f, g, h); // undefined, undefined, undefined
Undefined가 나오는 이유는 f, g, h에 아무런 값이 할당되지 않았기 때문이다. Undefined 대신 다른 값이 나오길 바라면 값을 할당해주면 된다.// 값을 직접 할당하는 방법
const {f = 4, g = 5, h: sixt = 6} = obj; // 기호(:)는 속성명 변경 시에 사용한다.
console.log(f, g, six); // 4, 5, 6
다른 예시: 배열 구조 분해
const arr1 = ["tomato", "kiwi", "banana"];
const [isTomato, isKiwi, isBanana] = arr1;
console.log(arr1, isTomato);
// 재할당할 때는 string은 따옴표 안에 쓸 필요 없는 것 같다.
[item1, item2, item3 = "bear"] = arr1;
console.log(item1, item2, item3);
// item3값을 bear로 줬지만 그 이후 arr1로 덮어씌웠기 때문에 결과는 arr1이 나온다.
// 만약 arr1[2]의 값이 없었다면 bear이 출력됐을 것.
let x = 1,
y = 3;
[x, y] = [y, x];
console.log("x :", x, "y :", y);
다른 예시: 객체 구조 분해
const obj = {
name: "Ah Young",
age: 20,
gender: "Female",
family: ["Father", "Mother"],
hello: function () {
console.log("Hello!!");
},
};
console.log(obj.name);
obj.name = "Christina";
console.log(obj.name); // 결과: christina
obj.hello();
console.log(obj.family[0]);
console.log(obj["name"]); // 결과: christina
obj.hobby = "영화"; // 키를 새로 추가해줄 수 있다.
console.log(obj.hobby);
console.log(obj["kdt-11"]); // undefined, 키 값을 추가해줘야 한다.
// obj.kdt-11 = "kdt-11기"; 바로 이렇게 쓸 때는 기호를 사용하면 안 된다.
obj.kdt11 = "kdt-11기";
// 또는
const obj1 = {
"kdt-11": "kdt-11기",
};
console.log(obj["kdt11"]);
console.log(obj1["kdt-11"]);
// 변수명이 중복될 경우 ex) age & age: New Age
const { name, hobby = "달리기", age } = obj;
console.log(name, hobby, age); //사용할 수 없는 변수명이라고 vs코드가 알려주는 건데, 무시해도 된다고 한다.
const { family, hello, age: newAge } = obj;
console.log(family, hobby, age);
문법
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
?. 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다. . 체이닝 연산자와 작동방식은 유사하나, 참조가 null 또는 undefined이라면, 에러가 발생하는 대신 표현식의 리턴 값은 undefined로 반환된다.undefined를 리턴한다.?.를 사용하면 참조나 기능이 undefined 또는 null일 때 연결된 객체의 값에 더욱 단순하게 접근할 수 있다.For Example 중첩된 구조를 가진 객체 데이터 (또는 배열, 함수 데이터)에서 하위 속성에 접근하기 전에 상위 속성의 상태(eg.null, undefiend, 또는 값이 존재한다던지..)에 따라 명시적으로 테스트하거나 단락시키지 않아도 된다.null 또는 undefiend인지 암묵적으로 확인하고, 만약 상위 속성이 null 또는 undefined이라면, 그 표현식은 자동으로 단락되어 undefined가 반환된다.예제
const fruit1 = {
name: 'Apple',
color: 'Red',
details: {
taste: 'sweet & sour',
texture: 'hard'
}
}
const fruit2 = {
name: 'Banana',
color: 'Yellow'
}
function getTexture(fruit) {
return fruit.details?.texture
}
console.log(getTexture(fruit1)) // hard
console.log(getTexture(fruit2)) // undefiend
// ?. 를 사용하지 않았다면 error가 발생했을 것이다.
삼항 연산자 & 선택적 체이닝 응용ver.
//'예제'의 함수 정의를 삼항 연산자로 한다.
const fruit1 = {
name: 'Apple',
color: 'Red',
details: {
taste: 'sweet & sour',
texture: 'hard'
}
}
const fruit2 = {
name: 'Banana',
color: 'Yellow'
}
function getTexture(fruit) {
return fruit.details?.texture || '입력 없음'
}
console.log(getTexture(fruit1)) // hard
console.log(getTexture(fruit2)) // 입력 없음
문법
if (조건) {
}
if (조건) {
} else {
}
if (조건1) {
} else if (조건2) {
} else if (조건3) {
} else {
}
예제
function isPositive(number){
if(number > 0){
return '양수입니다'
} else if (number < 0){
return '양수가 아닙니다'
}
else {
return 0
}
}
console.log(isPositive(3)) // 양수입니다
console.log(isPositive(-2)) // 양수가 아닙니다
console.log(isPositive(0)) // 0
문법
Switch (조건) {
case 값1:
// 조건이 '값1'일 때 실행
break
// 조건이 충족되면 다음 값으로 넘어가지 않음
case 값2:
// 조건이 '값2'일 때 실행
break
default:
// 조건이 '값1'도 '값2'도 아닐 때 실행
}
예제: swith 조건문 & 함수의 return (break 대신)
function bearFamily(member) {
switch (member) {
case 'Daddy':
return '아빠곰은 뚱뚱해'
case 'Mommy':
return '엄마곰은 날씬해'
case 'Baby':
return '새끼곰은 너무너무 귀여워'
default:
return '으쓱~으쓱~ 잘한다!'
}
}
console.log(bearFamily('Daddy')) // 아빠곰은 뚱뚱해
console.log(bearFamily('Mommy')) // 엄마곰은 날씬해
console.log(bearFamily('Baby')) // 새끼곰은 너무너무 귀여워
console.log(bearFamily('')) // 으쓱~ 으쓱~ 잘한다!
예제를 if 조건문으로 바꿔보기
function bearFamily(member) {
if (member === 'Daddy') {
return '아빠곰은 뚱뚱해'
} else if (member === 'Mommy') {
return '엄마곰은 날씬해'
} else if (member === 'Baby') {
return '새끼곰은 너무너무 귀여워'
} else {
return '으쓱~으쓱~ 잘한다!'
}
}
console.log(bearFamily('Daddy')) // 아빠곰은 뚱뚱해
문법
for (초기화; 조건; 증감) {
// 반복 실행할 코드
}
예제
for (let i = 9; i > -1; i -=1 ) {
if (i % 2 === 0){
continue //현재 반복문 중단 안하고 다음 반복문으로 넘어간다.
}
console.log(i) // 9, 7, 5, 3, 1
}
문법
for (반복하려는 배열 데이터 각각의 값을 반환받을 변수 of 반복하려는 배열 데이터) {
}
예제: <for vs for of> - for 반복문
const fruits = ['Apple', 'Banana', 'Melon']
for (let i = 0; i < fruits.length; i += 1) {
console.log(fruits[i])
} // Apple, Banana, Melon
예제: <for vs for of> - for of 반복문
const fruits = ['Apple', 'Banana', 'Melon']
for (const fruit of fruits) {
console.log(fruit)
} // Apple, Banana, Melon
예제2: <for vs for of> - 여러 객체 데이터를 포함하고 있는 배열 데이터일 경우
const rooms = [
{
number: 101,
guest: 'A'
},
{
number: 102,
guest: 'B'
},
{
number: 103,
guest: 'C'
}
]
for (let i = 0; i < rooms.length; i += 1) {
console.log(rooms[i].number) // 101, 102, 103
}
for (const room of rooms) {
console.log(room.number) // 101, 102, 103
}
문법
객체 데이터 = {
\\: ' ',
\\: ' '
}
for (각각의 객체 데이터를 입력받을 변수 in 객체 데이터) {
}
예제
const room101 = {
floor: '5f',
guest: 'A',
checkIn: '15:00',
checkOut: '12:00',
};
for (const key in room101) {
// 속성의 갯수만큼 반복된다.
// 단, 속성의 입력 순서와 출력 순서가 일치하지 않을 수 있다.
console.log(key)
// 대괄호 표기법을 사용하면 반복되는 속성 이름 위치에 key라는 변수로 그때그때 들어가져서 해당되는 내용을 조회하게 된다.
console.log(room101[key]);
}
문법
while (조건) {
}
예제
let n = 0
// 무한반복 출력
while (n < 4) {
console.log(n)
}
예제
let n = 0
// = 4 미만까지 숫자를 출력한다.
while (n < 4) {
console.log(n)
n += 1
}
Do while 반복문의 실행 순서는 중괄호 안의 내용이 먼저고, 그 다음이 조건이다.문법
let n = 0
do {
//실행할 내용
} while (조건)
예제 - 0~3까지 1씩 증가시켜 출력하기
let n = 0;
do {
console.log(n);
n += 1;
} while (n < 4);