I am learning JavaScript, and I do not understand what is the execution sequence of 2nd line. Please advise!
let envArr;
const envName = envArr && envArr[0] ? envArr[0] : "env1";
I am learning JavaScript, and I do not understand what is the execution sequence of 2nd line. Please advise!
let envArr;
const envName = envArr && envArr[0] ? envArr[0] : "env1";
2
Answers
1.envArr && envArr[0]
2. true:envArr[0]
false:"env1"
Here output of
envArr && envArr[0]
would be considered for execution of ternary operator.On other hand doing something like this (it’s illogical, but just for sake of example) –
Will execute ternary operation based on solely
envArr[0]
and it’s output will be anded withenvArr
, simplified version will look like this.BTW better way of doing above check from your question will be like this –
We are using optional chaining, you can find more details about optional chaining here