JavaScript
[JavaScript] ??=
hid1
2023. 12. 1. 18:53
x ??= 2
??= 코드를 처음 보았다. 추측을 하면 '아마 x가 null이나 undefined (널 병합 연산자) 면 x에 2로 할당한다는 의미이지 않을까?'는 생각이 들었고 찾아보니 내 예상이 맞았다.
const a = { duration: 50 };
a.duration ??= 10;
console.log(a.duration);
// Expected output: 50
a.speed ??= 25;
console.log(a.speed);
// Expected output: 25
a.duration의 값이 50이니 그대로 아웃풋은 50이 나오고 a 객체에 speed란 값이 없으니 25로 할당이 된다.
생각해보면 x += 1, x -= 1와 비슷한 연산자들일 뿐...
찾아보니 ??= 이외에도 &&=, ||= 등등 있었고 나중에 사용할 일 있으면 써봐야겠다.
반응형