david david - 2 months ago 31
Javascript Question

javascript: setting default value with IF statement instead of OR

I'm only sharing a small bit of code because there is so much going on, and I hope this is enough to answer my question.

I have some existing JS where a value is determined with an OR statement and I think I need to convert that to an IF statement. The final output is currently giving me both values if they both exist, and I only want "question" where both "question" and "name" values exist.

var question = new fq.Question(questionData.answerId, topicId,
questionData['question'] || questionData['name'],

Instead of using the OR operator (
answerData['question'] || answerData['name']
), I'd like to do something similar to the following:

if (questionData['question'] is undefined) {
use questionData['question'];
} else {
use instead questionData['name']

But, I don't know how I might accomplish such a statement within the
in the existing code pasted above. The name variable/value is always present, so there's no risk in defaulting to that. Question is only defined some of the time. And I don't ever want both appearing.

This is probably outside of the scope of my query here, but to fill in a little more detail, this code eventually outputs JSON files for topics and questions. Topics only have names values, and questions have both names and questions, but I only want the questions json to include questions values, not names. I'm pretty sure this is the key part in all of the JS to determin


Create a function and get value from there.

Need to remember scope of function:

Example Snippet:

var that = this;
var question = new fq.Question(questionData.answerId, topicId,

function getValue() {
  if (questionData['question']) { //null and undefined both are false
    return questionData['question']
  } else {
    return questionData['name']