Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best alternative for optional chaining in javascript

I have the following chaining operator

const age = data.student?.age ? data.student.age: '';

this works fine in my local machine but seems to have problem in another machine. on further investigation i could understand that node js lower version(i suppose version below 12) doesn't support chaining operator. I understand that i can replace this with if condition like below but would like to know suggestions on what is the best possible alternative for this.

function checkAge(data){
  if(data && data.student && data.student.age) {
    return data.student.age;
  } else {
   return '';
  }
}


const age  = checkAge(data);
like image 964
Shareer Avatar asked Dec 02 '25 17:12

Shareer


2 Answers

There is no need for code change. You only need to modify the target option in your TypeScript configuration and set it to anything ES2019 or below. Then you can use optional chaining in your TypeScript code and the compiler will produce the equivalent code.

The TypeScript code

const foo = a?.b?.c;

becomes

"use strict";
var _a;
const foo = (_a = a === null || a === void 0 ? void 0 : a.b) === null || _a === void 0 ? void 0 : _a.c;

when compiled: Playground Link

like image 171
VLAZ Avatar answered Dec 05 '25 08:12

VLAZ


If the problem is readability, you could probably try object destructing. So, your assigment would look something like this:

const {
  student: {
    age = ''
  } = {}
} = data
like image 28
Shahin Nazer Avatar answered Dec 05 '25 08:12

Shahin Nazer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!