[JS]ES6 문법 정리

김호중·2023년 10월 18일
0

javascript

목록 보기
3/9

참고자료

1. Shorthand property names

객체 관련한 문법이다.

// 기본적인 문법
const obj1 = {
  name: "ghwnd",
  age: 25
}

const name = "ghwnd"
const age = 25

const obj2 = {
  name: name,
  age: age
}

const obj3 = {
  name,
  age
}

//* 여기서 obj2와 obj3은 같은 의미이다.

2. Destructruing Assigment

객체 관련한 문법이다. 이는 배열에서도 공통적으로 사용 가능하다.

const student = {
  name: "ghwnd",
  age: 25
}

// 불편한 사용법
const name = student.name
const age = student.age

// es6문법**
const {name, age} = student
// 여기서 추가적으로 객체 내 속성의 이름을 바꾸고 싶다면 ":"를 사용하면 된다.
const {name:이름, age:나이} = student

3. Spread Syntax

문법은 아래와 같다.
...item
이 때 item 내의 child들을 반환한다고 생각하면 된다.

예시 마지막 코드를 보면 spread연산자는 item의 주소의 값 자체를 참조하는 것을 알 수 있다.

const obj1 = { key: "key1"}
const obj2 = { key: "key2"}

const array = [obj1, obj2]
>>> [{key: "key1"}, {key: "key2"}]
const copyArray = [...array]
>>> [{key: "key1"}, {key: "key2"}]

// spead 연산자와 더불어 key추가도 가능하다.
const copyArray2 = [...array, {key: "key3"}]
>>> [{key: "key1"}, {key: "key2"}, {key: "key3"}]

// 여기서 중요한 점**(위에 설명) = 주소의 값을 참조한다.
obj1.key = "newKey"

console.log(array, copyArray1, copyArray2)
>>> [{key: "newKey"}, {key: "key2"}] 
>>> [{key: "newKey"}, {key: "key2"}] 
>>> [{key: "newKey"}, {key: "key2"}, {key: "key3"}] 

4. Default parameters

함수를 정의 할때, 파라미터에 디폴트 값을 지정해주는 것이다.

function printMassage(massage = "defaultmassage"){
  console.log(massage)
}
printMassage("hello")
>>> hello
printMassage()
>>> defaultmassage

5. 삼항연산자

item ? trueFunction : falseFunction

6. Template Literals

문자열에 변수를 추가하는 방식이다.
백틱 `으로 감싸서 사용할 수 있으며, 변수는 ${} 안에서 사용한다.

const name = "ghwnd"
const age = "25"
console.log(`my name is ${name} and age is ${age}`)

7. Optional chaining

객체내의 키값이 없을 수도 있다는 것을 보장해주는 문법이다.

const person1 = {
  name: "ghwndrla"
  job: {
  	title: "SW"
  	manager:{
  		name: "bob"
	}
  }
}
const person2 = {
  name: "ghwnd"
}

function printPerson1(person){
  console.log(person.job.manager.name)
}
function printPerson2(person){
  console.log(person.job?.manager?.name)
}
              
printPerson1(person1)
>>> 정상출력
printPerson1(person2)
>>> 정상출력
  
printPerson2(person1)
>>> 정상출력
printPerson2(person2)
>>> error - key값이 없으므로.

profile
개발의 흔적을 남기고 쌓아가기 위한 일기장

0개의 댓글