skip to Main Content

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. 1.envArr && envArr[0]
    2. true:envArr[0]
    false:"env1"

    Login or Signup to reply.
  2. 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) –

    envArr && (envArr[0] ? envArr[0] : "env1");
    

    Will execute ternary operation based on solely envArr[0] and it’s output will be anded with envArr, simplified version will look like this.

    envArr && output_of_ternary
    

    BTW better way of doing above check from your question will be like this –

    const envName = envArr?.[0] || 'env1'
    

    We are using optional chaining, you can find more details about optional chaining here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search