Optional chaining
Optional chaining ?. trong JavaScript là cách an toàn để tham chiếu property mà không gây error ngay cả khi object reference là null hoặc undefined.
Vấn đề khi tham chiếu property gây error
Trong JavaScript, việc tham chiếu property của null hoặc undefined sẽ gây error.
jsconstbook =undefined ;consttitle =book .title ;constauthor = null;constauthor .
jsconstbook =undefined ;consttitle =book .title ;constauthor = null;constauthor .
Để tránh error, cần kiểm tra xem giá trị có phải null hoặc undefined không.
jsconstbook =undefined ;consttitle =book === null ||book ===undefined ?undefined :book .title ;console .log (title );
jsconstbook =undefined ;consttitle =book === null ||book ===undefined ?undefined :book .title ;console .log (title );
jsconstbook = {title : "Survival TypeScript" };consttitle =book === null ||book ===undefined ?undefined :book .title ;console .log (title );
jsconstbook = {title : "Survival TypeScript" };consttitle =book === null ||book ===undefined ?undefined :book .title ;console .log (title );
Với object lồng nhau, xử lý kiểm tra càng trở nên phức tạp.
jsconstbook = {author : {constauthorEmail =book === null ||book ===undefined ?undefined :book .author === null ||book .author ===undefined ?undefined :book .author .
jsconstbook = {author : {constauthorEmail =book === null ||book ===undefined ?undefined :book .author === null ||book .author ===undefined ?undefined :book .author .
Kiểm tra thì code chạy không error, nhưng lượng code viết ra lại nhiều.
Cú pháp Optional chaining
Optional chaining trong JavaScript là cách viết giúp tránh tham chiếu nhầm property của null hoặc undefined, đồng thời giảm lượng code. Optional chaining sử dụng operator ?..
jsconstbook =undefined ;consttitle =book ?.title ;// ^^Optional chainingconsole .log (title );
jsconstbook =undefined ;consttitle =book ?.title ;// ^^Optional chainingconsole .log (title );
jsconstbook = {title : "Survival TypeScript" };consttitle =book ?.title ;console .log (title );
jsconstbook = {title : "Survival TypeScript" };consttitle =book ?.title ;console .log (title );
Optional chaining có thể sử dụng lồng nhau.
jsconstbook =undefined ;constauthorEmail =book ?.author ?.console .log (authorEmail );
jsconstbook =undefined ;constauthorEmail =book ?.author ?.console .log (authorEmail );
jsconstbook = {author : {constauthorEmail =book ?.author ?.console .log (authorEmail );
jsconstbook = {author : {constauthorEmail =book ?.author ?.console .log (authorEmail );
Nếu biến hoặc property đứng trước ?. có giá trị null hoặc undefined, các property phía sau sẽ không được evaluate và trả về undefined.
jsconstbook = null;console .log (book ?.title );
jsconstbook = null;console .log (book ?.title );
jsconstbook = {author : null };console .log (book .author ?.name );
jsconstbook = {author : null };console .log (book .author ?.name );
Gọi function
Optional chaining cũng có thể sử dụng khi gọi function. Khi dùng với function, viết ?. trước dấu ngoặc argument.
jsconstincrement =undefined ;constresult =increment ?.(1);console .log (result );
jsconstincrement =undefined ;constresult =increment ?.(1);console .log (result );
jsconstincrement = (n ) =>n + 1;constresult =increment ?.(1);console .log (result );
jsconstincrement = (n ) =>n + 1;constresult =increment ?.(1);console .log (result );
Gọi method cũng viết tương tự.
jsconstbook = {getPrice :undefined };console .log (book .getPrice ?.());
jsconstbook = {getPrice :undefined };console .log (book .getPrice ?.());
jsconstbook = {getPrice () {return 0;},};console .log (book .getPrice ?.());
jsconstbook = {getPrice () {return 0;},};console .log (book .getPrice ?.());
Tham chiếu phần tử array
Optional chaining cũng có thể sử dụng khi tham chiếu phần tử array. Khi tham chiếu phần tử, viết ?. trước dấu ngoặc vuông.
jsconstbooks =undefined ;consttitle =books ?.[0];console .log (title );
jsconstbooks =undefined ;consttitle =books ?.[0];console .log (title );
jsconstbooks = ["Survival TypeScript"];consttitle =books ?.[0];console .log (title );
jsconstbooks = ["Survival TypeScript"];consttitle =books ?.[0];console .log (title );
Type trong TypeScript
Khi sử dụng optional chaining trong TypeScript, type của giá trị nhận được là union type của type property cuối cùng và undefined.
tsletbook : undefined | {title : string };consttitle =book ?.title ;
tsletbook : undefined | {title : string };consttitle =book ?.title ;
Kết quả compile của TypeScript
Khi compiler option target của TypeScript là es2020 trở lên, optional chaining được compile nguyên vẹn sang JavaScript.
tsconst title = book?.title;
tsconst title = book?.title;
Khi target là es2019 trở xuống, sẽ được compile thành code sử dụng ternary operator như sau.
tsconst title = book === null || book === void 0 ? void 0 : book.title;
tsconst title = book === null || book === void 0 ? void 0 : book.title;
Kết hợp với Nullish coalescing operator
Khi optional chaining trả về undefined và muốn gán giá trị default, có thể sử dụng Nullish coalescing operator ??.
jsconstbook =undefined ;consttitle =book ?.title ?? "Default title";console .log (title );
jsconstbook =undefined ;consttitle =book ?.title ?? "Default title";console .log (title );
Chia sẻ kiến thức
・Optional chaining ?. trong JavaScript là cách tham chiếu property an toàn
・Khi giá trị là null hoặc undefined, trả về undefined
・Có thể lồng nhau như a?.b?.c
・Với function là ?.()
・Với array là ?.[]
・Trong TypeScript, type là union của type giá trị và undefined
・Kết hợp tốt với Nullish coalescing operator
Từ 『Survival TypeScript』
Thông tin liên quan
📄️ Truy cập phần tử array
Truy cập phần tử array trong JavaScript
📄️ Toán tử ba ngôi
Toán tử ba ngôi (ternary operator) trong JavaScript là toán tử có thể thực hiện điều kiện phân nhánh. Được gọi là toán tử ba ngôi vì nhận ba toán hạng: biểu thức điều kiện, giá trị khi đúng, và giá trị khi sai.