이 글은 최근에 접한 새로운 JS 문법에 대한 아카이빙입니다.
structuredClone
JavaScript의 객체는 별도 변수에 복사할 때 참조된 메모리 주소를 복사하기 때문에 객체 전이(Mutation)가 일어난다. 객체 전이는 쉽게 말하자면 복사해서 만든 객체의 값을 변경했을 때 원본 객체에도 영향을 주는 것을 말합니다.
그러다보니 원본 객체에 영향을 주지 않는 복사(deep copy)를 위해서 JSON.parse, JSON.stringify를 활용하거나 lodash라이브러리를 사용하는 등의 방법이 있었습니다. 이번에 객체 복사를 위해 ECMA에 추가된 메서드가 있어서 소개합니다.
- 기본 문법
structuredClone(value)
structuredClone(value, options)
- 사용
const A = {
name : 'Jay'
};
const B = structuredClone(A);
B.name = 'Chris';
console.log(A.name); // Jay
console.log(B.name); // Chris
MDN 문서, WorkerGlobalScope: structuredClone() method
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
The structured clone algorithm - Web APIs | MDN
The structured clone algorithm copies complex JavaScript objects. It is used internally when invoking structuredClone(), to transfer data between Workers via postMessage(), storing objects with IndexedDB, or copying objects for other APIs.
developer.mozilla.org
?= Operator
: Safe Assignment Operator
(ECMA 표준에 포함되었는지 확인 필요)
기존에는 비동기 처리에 대한 에러 핸들링 코드를 Try catch로 감싸서 한 블럭 이상 코드를 작성해야 했지만, 이 새로운 ?= 할당연산자는 이러한 수고를 한 줄로 줄여줍니다.
- 예시 (출처 하단 기입의 "Bye Bye, Try-Catch Blocks: Meet JavaScript's Safe Assignment Operator Proposal😉")
const [error, data] ?= await fetch("https://api.example.com");
Effortless Error Handling in JavaScript: How the Safe Assignment Operator Simplifies Your Code
Effortless Error Handling in JavaScript: How the Safe Assignment Operator Simplifies Your Code
Error handling in JavaScript can be messy. Wrapping large blocks of code in try/catch statements...
dev.to
Say Goodbye to Try/Catch with This New ECMAScript Operator!
Introducing the ?= Operator: JavaScript’s New Error Handling Hero
Say Goodbye to Try/Catch with This New ECMAScript Operator! 🚀
Introducing the ?= Operator: JavaScript’s New Error Handling Hero
javascript.plainenglish.io
Reddit의 pros and cons (흥미 진진 😎🍿)
https://www.reddit.com/r/javascript/comments/1ew7fkr/what_are_your_opinions_on_this_draft_for/
From the javascript community on Reddit: What are your opinions on this draft for ECMAScript Error Safe Assignment Operator?
Explore this post and more from the javascript community
www.reddit.com
JavaScript Safe Assignment Operator (?=): A Complete Guide
Introduction to the Safe Assignment Operator (?=) in JavaScript
JavaScript is introducing a new operator, ?=, called the Safe Assignment Operator. This operator is designed to simplify error handling in…
medium.com
'Programming > ☕ JavaScript' 카테고리의 다른 글
Debounce, Throttle 이해하고 구현해보기 (1) | 2024.12.31 |
---|---|
[실무에서 필요했던 단단한 기초 시리즈] 분기처리에 사용하는 연산자 뽀개기 (feat. falsy, nullish, &&, ||, ??) (0) | 2024.03.11 |
[node] console 메서드 (테이블형식출력, 성능측정, 객체출력) (0) | 2022.08.27 |
[keyboard event] 키 입력시 입력값 검증 (0) | 2021.12.20 |