0

I have a code below using if/else condition to evaluate what value to assign addedDocument based on whether customId is not Null.

Why is it that addedDocument cannot be found as seen in the picture below?

if (customId) {
  const addedDocument = await setDoc(doc(ref), {
    ...documentData,
    createdAt,
  });
} else {
  const addedDocument = await addDoc(ref, { ...documentData, createdAt });
}

dispatchIfNotCancelled({
  type: 'ADDED_DOCUMENT',
  payload: addedDocument,
});

if/else operator causing variable to not be found

But can be found when using a ternary operator? As seen in the picture below

const addedDocument = customId
  ? await setDoc(doc(ref, customId), { ...documentData, createdAt })
  : await addDoc(ref, { ...documentData, createdAt });

dispatchIfNotCancelled({
  type: 'ADDED_DOCUMENT',
  payload: addedDocument,
});

Ternary operator having no error

  • [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) variables are block-scoped. – Nalin Ranjan Dec 16 '21 at 08:03
  • Read the differences about declaring variables with var, let and const keywords. var is function scoped, which means it is available only within the function, where you declare it. let and const are block scoped, so if you declare them within scope {} , they are available only there. – Tigran Petrosyan Dec 16 '21 at 08:33
  • Thanks. I always thought the scope only means function { }. Didn't knew that if/else { } was also consider a scope. – Norman Wong Dec 16 '21 at 13:47

0 Answers0