7주차 - 자바스크립트 최신 문법 정리

김윤경·2023년 5월 22일
0
post-thumbnail

2023.05.22

자바스크립트 최신 문법 정리

출처 : https://www.youtube.com/watch?v=36HrZHzPeuY

01. Shorthand property names

const name = "Yun";
const age = "23";

const Yun1 = {
  name : name,
  age : age,
};

위의 예시 코드처럼 이름과 나이가 미리 정의가 되어 있다면,
Yun1의 name이라는 key에는 "Yun"이라는 값이 들어가고, Yun1의 age라는 key에는 "23"이라는 값이 들어간다.

😊 이 경우에는 key와 value의 이름이 같으므로, 아래의 코드처럼 축약해서 작성할 수 있다.

const Yun2 = {
  name,
  age,
};

02. Destructing assignment

// object
const student = {
  name : "Anna",
  levle : 1,
};
// 💩
const name = student.name;
const level = student.level;

object의 key와 value에 접근하기 위해서는 💩에 작성한 코드처럼 작성해야되지만,

// ✨
const {name, level} = student;

위의 코드처럼 object의 key 이름을 { } 안에 정의해주고, = object 이름 을 작성하면 object 안에 들어있는 value들이 각각 key에 맞게 할당되어서 출력된다.

😊 만약에 key의 이름을 변경하고 싶다면, 아래의 코드처럼 작성하면 된다.

const {name : studnetName, level : studentLevel} = student;

📌 주의해야 될 점
: key의 이름을 변경했다면 출력할 때에도 변경한 이름을 사용해야 된다.

배열인 경우에도 똑같이 활용할 수 있다.

//array
const animals = ["cat", "dog"];
// 💩
const first = animal[0];
const second = animal[1];
// ✨
const [first, second] = animals;

📌 주의해야 될 점
: object인 경우에는 { }, array인 경우에는 [ ] 를 사용해야된다.

03. Spread Syntax

const obj1 = {key : "key1"};
const obj2 = {key : "key2"};
const array1 = [obj1, obj2];

위의 코드에서 배열을 복사할 때, map이나 foreach를 사용하여 복사할 수도 있지만, spread syntax를 이용하여 아래의 코드처럼 간단하게 배열을 복사할 수 있다.

const arrayCopy = [...array];

➡ . . . 은 array에 들어있는 item을 하나하나 가져와서 복사하는 것을 의미한다.

😊 새로운 item을 추가하고 싶은 경우에는 아래의 코드처럼 하면 된다.

const arrayCopy2 = [...array, {key : "key3"}];

📌 중요한 포인트1 !
: spread syntax를 이용하여 복사되는 값들은 모두 주소값만 복사되어 오기 때문에 전부 동일한 object를 가리키고 있다.
➡ 그래서 만약 값을 변경하게 된다면 복사된 값도 변경되는 것을 알 수 있다.

📌 중요한 포인트2 !
: 배열은 [ ] 를, object는 { } 를 이용해야 된다.

const obj3 = {...obj1};
console.log(obj3); // {key : "key1"}

또한, 이를 활용해서 배열이나 object를 합치는 것도 가능하다.

// array concatenation
const fruit1 = ["peach", "apple"];
const fruit2 = ["banana", "kiwhi"];
const fruits = [...fruit1, ...fruit2];
// ["peach", "apple", "banana", "kiwhi"]
//
// object concatenation
const dog = {dog : "dog"};
const cat = {cat : "cat"};
const animal = {...dog, ...cat};
// {dog : "dog", cat : "cat"}

📌 주의해야 될 점
: key의 이름이 동일한 object를 병합하는 경우에 제일 뒤에 오는 key가 첫 번째 key를 덮어씌운다.

04. Default parameters

function printMessage(message) {
  if (message == null) {
    message = "default message";
  }
  console.log(message);
}
// code 1
printMessage("hello"); // hello
// code 2
printMessage(); // undefined

code 1처럼 function의 message라는 인자에 "hello"라는 값을 넣은 경우에는 정상적으로 출력되지만,
code2와 같이 아무런 인자를 넣지 않는다면 function에 if 조건문을 사용해서 message의 값이 없는 조건을 추가해줘야 된다.

function prinMsg(msg = "default message") {
  console.log(msg);
}
// code 3
printMsg("hello");
// code 4
printMsg();

😊 하지만 위의 코드처럼 fuction의 인자값에 = "default message" 처럼 초기값을 설정 하면 if 조건문을 사용하지 않아도 된다.

05. Ternary Operator

const isCat = true;
// 💩
let component;
if (isCat) {
  component = "cat";
}else {
  component = "dog";
}
// ✨
const component = isCat ? "cat" : "dog";

💩에 작성된 코드처럼 isCat이라는 변수가 true인지 false인지에 따라서 값을 설정하고 싶은 경우에는 조건문을 사용하는데, 이러한 경우에는 ternary operator를 사용하여 간단하게 코드를 줄일 수 있다.

✨에 작성된 코드처럼 component에 isCat이 true라면 (? 뒤에 오는 값) "cat", false라면 (: 뒤에 오는 값) "dog"를 출력하는 것이다.

😊 위의 방법은 react에서 자주 사용되는 방법이다.

06. Template Literals

const weather = "⛅";
const temparature = "16";
// 💩
console.log(
  "Today weather is " + weather + " and temparature is " + temparature + "."
);
// ✨
console.log("Today weather is ${weather} and temparature is ${temparature}.");

💩처럼 ""와 + 를 사용하여 변수값을 넣어서 문장을 만들 수 있는데,
✨처럼 ${ }를 사용하여 코드를 더욱 간단하게 변경할 수도 있다.

07. Optional Chaining

const person1 = {
  name : "Yun",
  job : {
    title : "student",
    professor : {
      name : "Bob",
    },
  },
};
const person2 = {
  name = "Bob",
};
// 💩💩💩
function printManager(person) {
  console.log(person.job.professor.name);
}
printManager(person1);
// Bob
printManager(person2);
// error 발생

💩💩💩의 코드처럼 printManager라는 function에서 person1을 출력하면 professor가 있기 때문에 바로 출력이 되지만, person2에는 job도, professor도 없기 때문에 error가 발생하게 된다.

😊 이러한 경우에는 아래의 코드처럼 작성해서 해결할 수 있다.

function printManager(person) {
  console.log(person.job && person.job.professor && person.job.professor.name);
}

하지만 위의 코드에서 person.job 이라는 값이 계속해서 반복되는 것을 알 수 있는데, 이는 아래의 코드처럼 줄일 수 있다.

function printManager(person) {
  console.log(person.job?.professor?.name);
}

😊 "person에 job이 있고, professor가 있다면 name을 출력해라 !" 라고 해석하면 된다.

08. Nullish Coalescing Operator

// Logical OR operator
// false : false, "", 0, null, undefined
const name = "Yun";
const userName = name || "Guest";
console.log(userName); // Yun

위의 코드처럼 OR 연산자는 앞의 값이 false인 경우에 뒤의 값이 출력되는 성질을 가지고 있다.
이러한 경우에는 null, "", 0 등을 name에 선언하여도, false 값으로 간주해서 "Guest"라는 값을 출력하게 된다.
(📌 실전에서 사용하면 버그가 될 위험이 높다.)

😊 이를 좀 더 명확하게 코딩하려면 아래의 코드처럼 하면 된다.

// code 1
const name = "";
const userName = name ?? "Guest";
console.log(userName); // 빈 문자열 출력
// code 2
const num = 0;
const message = num ?? "undefined";
console.log(message); // 0

code 1의 경우에는 "name에 값이 있다면 name을 출력하고, 없다면 "Guest"를 출력해라"라는 뜻이고,
code 2의 경우에는 "num에 값이 있다면 num을 출력하고, num의 값이 없을 때만 "undefined"를 출력해라"라는 뜻이다.

09. 마무리

JavaScirpt 알고리즘 문제를 풀 때, 모르는 문제가 있으면 검색해서 찾아봤는데, 그 때 모르는 문법들이 많았었다. 그런데 이번 강의를 통해서 문법들에 대해서 정확하게 알 수 있었고 쉽게 이해할 수 있었다. 물론 좀 더 연습이 필요하겠지만, 알고리즘 문제를 더 잘 풀 수 있게 된 것 같다. (아마도 . . . ?) 🤣

0개의 댓글