728x90
반응형

js 연산자 표를 볼 때마다 아 이런 게 있구나~ 하면서 넘겨왔던 ?? 연산자
처음 봤을 땐 저런게 있구나~ 하는 생각으로 넘겼지만 react 에서 저 연산자를 볼 줄은 몰랐다
undefined 나 null를 내지 않고 확실한 결과값을 내기 위해 사용하는데
??
사용 전
function test(food,price,num){
let foodPrice = num*price
console.log(price)
console.log(food +"과 "+foodPrice+"원")
}
// 결과
test("빵",5000,2)
5000
'빵과 10000원'
// null 지정 시
test("밥",null,2)
null
'밥과 0원'
// undefined 지정 시
test("면",undefined,2)
undefined
'면과 NaN원'
null 이나 undefined 가 들어가면 바로 null,undefined 을 뱉어버린다
?? 연산자는 값을 확실하게 하기 위해 디폴트 값을 지정할 수 있다
function test2(food,price,num){
let prices = price ?? 5000
console.log(prices)
let foodPrice = num*prices
console.log(food +"과 "+foodPrice+"원")
}
// 결과
// null 지정 시
test2("밥",null,3)
5000
'밥과 15000원'
// undefined 지정 시
test2("면",undefined,3)
5000
'면과 15000원'
null 이나 undefined 를 대비하기 위해 디폴트 값을 지정해 준다는 게 정말 좋은 점 같다
typescript를 사용하며 데이터를 바꾸는 함수를 사용했을 때
값이 undefined로 떠 삼항자로 모두 ""를 넣어줬는데 이제... 저 연산자를 넣어주면 좋을 거 같단 생각이 든다.
728x90
반응형
'TIL' 카테고리의 다른 글
next.js 왜 사용하나요 (2) | 2023.02.26 |
---|---|
js 느낌표 두개 연산자 (0) | 2023.02.26 |
타입스크립트 any, unknown (0) | 2023.02.26 |
useEffect counter로 작동 순서 정리 (0) | 2023.02.21 |
'string' 형식은 '--downlevelIteration' 플래그 또는 'es2015' 이상의 '--target'을 사용하는 경우에만 반복할 수 있습니다. (0) | 2023.02.09 |
댓글