Unable to do a proper check before assigning a variable Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Unable to do a proper check before assigning a variable without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following code

let sess = session

let vigilances = sess.usuario.empresasVigi || 0;
let idSess = sess.sesionUsuarioSessionStorage.sesionExt || null;
let balance = sess.saldosUsuarioSessionStorage.saldo || 0;

Sess is an object, but sometimes it is empty so some properties will be missing If that happens I want the variable to be assigned the value after ||, so I have written the code above

But so far , im receiving

Cannot read property 'empresasVigi' of undefined

Answer

Use optional chaining

let vigilances = sess.usuario?.empresasVigi || 0;
let idSess = sess.sesionUsuarioSessionStorage?.sesionExt || null;
let balance = sess.saldosUsuarioSessionStorage?.saldo || 0;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

We are here to answer your question about Unable to do a proper check before assigning a variable - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji